chore(i18n,curriculum): update translations (#42487)
* chore(i18n,curriculum): update translations * chore: Italian to italian Co-authored-by: Nicholas Carrigan <nhcarrigan@gmail.com>
This commit is contained in:
@ -0,0 +1,89 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392ca
|
||||
title: Accedere ai dati degli Array con gli indici
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBZQbTz'
|
||||
forumTopicId: 16158
|
||||
dashedName: access-array-data-with-indexes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Possiamo accedere ai dati all'interno degli array utilizzando gli <dfn>indici</dfn>.
|
||||
|
||||
Gli indici degli array sono scritti nella stessa notazione tra parentesi usata dalle stringhe, tranne per il fatto che invece di specificare un carattere, specificano una voce nell'array. Come le stringhe, gli array utilizzano l'indicizzazione <dfn>zero-based</dfn>, quindi il primo elemento in un array ha un indice di `0`.
|
||||
|
||||
<br>
|
||||
|
||||
**Esempio**
|
||||
|
||||
```js
|
||||
var array = [50,60,70];
|
||||
array[0];
|
||||
var data = array[1];
|
||||
```
|
||||
|
||||
`array[0]` ora è `50` e `data` ha il valore `60`.
|
||||
|
||||
**Nota:** Non ci dovrebbero essere spazi tra il nome dell'array e le parentesi quadre, come in `array [0]`. Anche se JavaScript è in grado di elaborarlo correttamente, questo potrebbe confondere altri programmatori che leggono il tuo codice.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Crea una variabile chiamata `myData` e impostala al primo valore di `myArray` usando la notazione a parentesi.
|
||||
|
||||
# --hints--
|
||||
|
||||
La variabile `myData` dovrebbe essere uguale al primo valore di `myArray`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (
|
||||
typeof myArray !== 'undefined' &&
|
||||
typeof myData !== 'undefined' &&
|
||||
myArray[0] === myData
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
Si dovrebbe accedere ai dati nella variabile `myArray` utilizzando la notazione a parentesi.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (code.match(/\s*=\s*myArray\[0\]/g)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined" && typeof myData !== "undefined"){(function(y,z){return 'myArray = ' + JSON.stringify(y) + ', myData = ' + JSON.stringify(z);})(myArray, myData);}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myArray = [50,60,70];
|
||||
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [50,60,70];
|
||||
var myData = myArray[0];
|
||||
```
|
@ -0,0 +1,71 @@
|
||||
---
|
||||
id: 56592a60ddddeae28f7aa8e1
|
||||
title: Accedere agli array multidimensionali con gli indici
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ckND4Cq'
|
||||
forumTopicId: 16159
|
||||
dashedName: access-multi-dimensional-arrays-with-indexes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
È possibile pensare a un array <dfn>multi-dimensionale</dfn>, come a un *array di array*. Quando utilizzi le parentesi per accedere al tuo array, il primo set di parentesi si riferisce alle voci nell'array più esterno (il primo livello), e ogni coppia di parentesi supplementare si riferisce al livello successivo delle voci all'interno.
|
||||
|
||||
**Esempio**
|
||||
|
||||
```js
|
||||
var arr = [
|
||||
[1,2,3],
|
||||
[4,5,6],
|
||||
[7,8,9],
|
||||
[[10,11,12], 13, 14]
|
||||
];
|
||||
arr[3];
|
||||
arr[3][0];
|
||||
arr[3][0][1];
|
||||
```
|
||||
|
||||
`arr[3]` è `[[10, 11, 12], 13, 14]`, `arr[3][0]` è `[10, 11, 12]`, e `arr[3][0][1]` è `11`.
|
||||
|
||||
**Nota:** Non ci dovrebbero essere spazi tra il nome dell'array e le parentesi quadre, come `array [0][0]` e anche questo non è permesso: `array [0] [0]`. Anche se JavaScript è in grado di elaborarlo correttamente, questo potrebbe confondere altri programmatori che leggono il tuo codice.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Utilizzando la notazione a parentesi seleziona un elemento da `myArray` in modo che `myData` sia uguale a `8`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myData` dovrebbe essere uguale a `8`.
|
||||
|
||||
```js
|
||||
assert(myData === 8);
|
||||
```
|
||||
|
||||
Dovresti usare la notazione parentesi per leggere il valore corretto da `myArray`.
|
||||
|
||||
```js
|
||||
assert(/myData=myArray\[2\]\[1\]/.test(__helpers.removeWhiteSpace(code)));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return "myData: " + myData + " myArray: " + JSON.stringify(myArray);})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myArray = [[1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14]];
|
||||
|
||||
var myData = myArray[0][0];
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [[1,2,3],[4,5,6], [7,8,9], [[10,11,12], 13, 14]];
|
||||
var myData = myArray[2][1];
|
||||
```
|
@ -0,0 +1,120 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cd
|
||||
title: Accedere ad Array annidati
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cLeGDtZ'
|
||||
forumTopicId: 16160
|
||||
dashedName: accessing-nested-arrays
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Come abbiamo visto in precedenti esempi, gli oggetti possono contenere sia oggetti nidificati che array nidificati. Simile all'accesso agli oggetti nidificati, la notazione a parentesi dell'array può essere concatenata per accedere agli array nidificati.
|
||||
|
||||
Ecco un esempio di come accedere a un array nidificato:
|
||||
|
||||
```js
|
||||
var ourPets = [
|
||||
{
|
||||
animalType: "cat",
|
||||
names: [
|
||||
"Meowzer",
|
||||
"Fluffy",
|
||||
"Kit-Cat"
|
||||
]
|
||||
},
|
||||
{
|
||||
animalType: "dog",
|
||||
names: [
|
||||
"Spot",
|
||||
"Bowser",
|
||||
"Frankie"
|
||||
]
|
||||
}
|
||||
];
|
||||
ourPets[0].names[1];
|
||||
ourPets[1].names[0];
|
||||
```
|
||||
|
||||
`ourPets[0].names[1]` sarebbe la stringa `Fluffy` e `ourPets[1].names[0]` sarebbe la stringa `Spot`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usando la notazione a punto e a parentesi, imposta la variabile `secondTree` al secondo elemento nella lista `trees` dall'oggetto `myPlants`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`secondTree` dovrebbe essere uguale alla stringa `pine`.
|
||||
|
||||
```js
|
||||
assert(secondTree === 'pine');
|
||||
```
|
||||
|
||||
Il tuo codice dovrebbe utilizzare la notazione a punti e parentesi per accedere a `myPlants`.
|
||||
|
||||
```js
|
||||
assert(/=\s*myPlants\[1\].list\[1\]/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(x) {
|
||||
if(typeof x != 'undefined') {
|
||||
return "secondTree = " + x;
|
||||
}
|
||||
return "secondTree is undefined";
|
||||
})(secondTree);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myPlants = [
|
||||
{
|
||||
type: "flowers",
|
||||
list: [
|
||||
"rose",
|
||||
"tulip",
|
||||
"dandelion"
|
||||
]
|
||||
},
|
||||
{
|
||||
type: "trees",
|
||||
list: [
|
||||
"fir",
|
||||
"pine",
|
||||
"birch"
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
var secondTree = "";
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myPlants = [
|
||||
{
|
||||
type: "flowers",
|
||||
list: [
|
||||
"rose",
|
||||
"tulip",
|
||||
"dandelion"
|
||||
]
|
||||
},
|
||||
{
|
||||
type: "trees",
|
||||
list: [
|
||||
"fir",
|
||||
"pine",
|
||||
"birch"
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
var secondTree = myPlants[1].list[1];
|
||||
```
|
@ -0,0 +1,99 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cc
|
||||
title: Accedere ad oggetti nidificati
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRnRnfa'
|
||||
forumTopicId: 16161
|
||||
dashedName: accessing-nested-objects
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Le sotto-proprietà degli oggetti possono essere accessibili concatenando insieme la notazione a punto o a parentesi.
|
||||
|
||||
Ecco un oggetto nidificato:
|
||||
|
||||
```js
|
||||
var ourStorage = {
|
||||
"desk": {
|
||||
"drawer": "stapler"
|
||||
},
|
||||
"cabinet": {
|
||||
"top drawer": {
|
||||
"folder1": "a file",
|
||||
"folder2": "secrets"
|
||||
},
|
||||
"bottom drawer": "soda"
|
||||
}
|
||||
};
|
||||
ourStorage.cabinet["top drawer"].folder2;
|
||||
ourStorage.desk.drawer;
|
||||
```
|
||||
|
||||
`ourStorage.cabinet["top drawer"].folder2` sarebbe la stringa `secrets`e `ourStorage.desk.drawer` sarebbe la stringa `stapler`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Accedi all'oggetto `myStorage` e assegna il contenuto della proprietà `glove box` alla variabile `gloveBoxContents`. Utilizza la notazione a punto per tutte le proprietà, se possibile, altrimenti utilizzare la notazione a parentesi.
|
||||
|
||||
# --hints--
|
||||
|
||||
`gloveBoxContents` dovrebbe essere uguale alla stringa `maps`.
|
||||
|
||||
```js
|
||||
assert(gloveBoxContents === 'maps');
|
||||
```
|
||||
|
||||
Il tuo codice dovrebbe utilizzare la notazione a punti e parentesi per accedere a `myStorage`.
|
||||
|
||||
```js
|
||||
assert(/=\s*myStorage\.car\.inside\[\s*("|')glove box\1\s*\]/g.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(x) {
|
||||
if(typeof x != 'undefined') {
|
||||
return "gloveBoxContents = " + x;
|
||||
}
|
||||
return "gloveBoxContents is undefined";
|
||||
})(gloveBoxContents);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myStorage = {
|
||||
"car": {
|
||||
"inside": {
|
||||
"glove box": "maps",
|
||||
"passenger seat": "crumbs"
|
||||
},
|
||||
"outside": {
|
||||
"trunk": "jack"
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var gloveBoxContents = undefined;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStorage = {
|
||||
"car":{
|
||||
"inside":{
|
||||
"glove box":"maps",
|
||||
"passenger seat":"crumbs"
|
||||
},
|
||||
"outside":{
|
||||
"trunk":"jack"
|
||||
}
|
||||
}
|
||||
};
|
||||
var gloveBoxContents = myStorage.car.inside["glove box"];
|
||||
```
|
@ -0,0 +1,103 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c8
|
||||
title: Accedere alle proprietà dell'oggetto con la notazione a parentesi
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBvmEHP'
|
||||
forumTopicId: 16163
|
||||
dashedName: accessing-object-properties-with-bracket-notation
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Il secondo modo di accedere alle proprietà di un oggetto è la notazione a parentesi (`[]`). Se la proprietà dell'oggetto a cui stai tentando di accedere ha uno spazio nel suo nome, è necessario utilizzare la notazione a parentesi.
|
||||
|
||||
Tuttavia, puoi ancora usare la notazione a parentesi sulle proprietà dell'oggetto senza spazi.
|
||||
|
||||
Ecco un esempio di come usare la notazione a parentesi per leggere la proprietà di un oggetto:
|
||||
|
||||
```js
|
||||
var myObj = {
|
||||
"Space Name": "Kirk",
|
||||
"More Space": "Spock",
|
||||
"NoSpace": "USS Enterprise"
|
||||
};
|
||||
myObj["Space Name"];
|
||||
myObj['More Space'];
|
||||
myObj["NoSpace"];
|
||||
```
|
||||
|
||||
`myObj["Space Name"]` sarebbe la stringa `Kirk`, `myObj['More Space']` sarebbe la stringa `Spock`, e `myObj["NoSpace"]` sarebbe la stringa `USS Enterprise`.
|
||||
|
||||
Nota che i nomi delle proprietà che contengono spazi devono essere tra virgolette (singola o doppia).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Leggi i valori delle proprietà `an entree` e `the drink` di `testObj` usando la notazione a parentesi e assegnali rispettivamente a `entreeValue` e `drinkValue`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`entreeValue` dovrebbe essere una stringa
|
||||
|
||||
```js
|
||||
assert(typeof entreeValue === 'string');
|
||||
```
|
||||
|
||||
Il valore di `entreeValue` dovrebbe essere la stringa `hamburger`
|
||||
|
||||
```js
|
||||
assert(entreeValue === 'hamburger');
|
||||
```
|
||||
|
||||
`drinkValue` dovrebbe essere una stringa
|
||||
|
||||
```js
|
||||
assert(typeof drinkValue === 'string');
|
||||
```
|
||||
|
||||
Il valore di `drinkValue` dovrebbe essere la stringa `water`
|
||||
|
||||
```js
|
||||
assert(drinkValue === 'water');
|
||||
```
|
||||
|
||||
Dovresti usare due volte la notazione a parentesi
|
||||
|
||||
```js
|
||||
assert(code.match(/testObj\s*?\[('|")[^'"]+\1\]/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b) { return "entreeValue = '" + a + "', drinkValue = '" + b + "'"; })(entreeValue,drinkValue);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var testObj = {
|
||||
"an entree": "hamburger",
|
||||
"my side": "veggies",
|
||||
"the drink": "water"
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var entreeValue = testObj; // Change this line
|
||||
var drinkValue = testObj; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var testObj = {
|
||||
"an entree": "hamburger",
|
||||
"my side": "veggies",
|
||||
"the drink": "water"
|
||||
};
|
||||
var entreeValue = testObj["an entree"];
|
||||
var drinkValue = testObj['the drink'];
|
||||
```
|
@ -0,0 +1,99 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c7
|
||||
title: Accedere alle proprietà dell'oggetto con la notazione a punti
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cGryJs8'
|
||||
forumTopicId: 16164
|
||||
dashedName: accessing-object-properties-with-dot-notation
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Esistono due modi per accedere alle proprietà di un oggetto: notazione a punti (`.`) e notazione a parentesi (`[]`), simile a un array.
|
||||
|
||||
La notazione a punti è quella che usi quando conosci già il nome della proprietà a cui stai tentando di accedere.
|
||||
|
||||
Di seguito è riportato un esempio di utilizzo della notazione a punti (`.`) per leggere la proprietà di un oggetto:
|
||||
|
||||
```js
|
||||
var myObj = {
|
||||
prop1: "val1",
|
||||
prop2: "val2"
|
||||
};
|
||||
var prop1val = myObj.prop1;
|
||||
var prop2val = myObj.prop2;
|
||||
```
|
||||
|
||||
`prop1val` ha il valore della stringa `val1` e `prop2val` ha il avere un valore della stringa `val2`.
|
||||
# --instructions--
|
||||
|
||||
Leggi i valori delle proprietà di `testObj` utilizzando la notazione a punti. Imposta la variabile `hatValue` in modo che sia uguale alla proprietà `hat` dell'oggetto, e imposta la variabile `shirtValue` in modo che sia uguale alla proprietà `shirt` dell'oggetto.
|
||||
|
||||
# --hints--
|
||||
|
||||
`hatValue` dovrebbe essere una stringa
|
||||
|
||||
```js
|
||||
assert(typeof hatValue === 'string');
|
||||
```
|
||||
|
||||
Il valore di `hatValue` dovrebbe essere la stringa `ballcap`
|
||||
|
||||
```js
|
||||
assert(hatValue === 'ballcap');
|
||||
```
|
||||
|
||||
`shirtValue` dovrebbe essere una stringa
|
||||
|
||||
```js
|
||||
assert(typeof shirtValue === 'string');
|
||||
```
|
||||
|
||||
Il valore di `shirtValue` dovrebbe essere la stringa `jersey`
|
||||
|
||||
```js
|
||||
assert(shirtValue === 'jersey');
|
||||
```
|
||||
|
||||
Dovresti usare due volte la notazione a punti
|
||||
|
||||
```js
|
||||
assert(code.match(/testObj\.\w+/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b) { return "hatValue = '" + a + "', shirtValue = '" + b + "'"; })(hatValue,shirtValue);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var testObj = {
|
||||
"hat": "ballcap",
|
||||
"shirt": "jersey",
|
||||
"shoes": "cleats"
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var hatValue = testObj; // Change this line
|
||||
var shirtValue = testObj; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var testObj = {
|
||||
"hat": "ballcap",
|
||||
"shirt": "jersey",
|
||||
"shoes": "cleats"
|
||||
};
|
||||
|
||||
var hatValue = testObj.hat;
|
||||
var shirtValue = testObj.shirt;
|
||||
```
|
@ -0,0 +1,121 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c9
|
||||
title: Accedere alle proprietà degli oggetti con le variabili
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cnQyKur'
|
||||
forumTopicId: 16165
|
||||
dashedName: accessing-object-properties-with-variables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Un altro uso della notazione a parentesi con gli oggetti è quello di accedere a una proprietà memorizzata come valore di una variabile. Questo può essere molto utile per iterare sulle le proprietà di un oggetto o quando si accede a una tabella di ricerca.
|
||||
|
||||
Ecco un esempio di utilizzo di una variabile per accedere a una proprietà:
|
||||
|
||||
```js
|
||||
var dogs = {
|
||||
Fido: "Mutt", Hunter: "Doberman", Snoopie: "Beagle"
|
||||
};
|
||||
var myDog = "Hunter";
|
||||
var myBreed = dogs[myDog];
|
||||
console.log(myBreed);
|
||||
```
|
||||
|
||||
La stringa `Doberman` sarà visualizzata nella console.
|
||||
|
||||
Un altro modo per utilizzare questo concetto è quando il nome della proprietà viene ottenuto dinamicamente durante l'esecuzione del programma, come segue:
|
||||
|
||||
```js
|
||||
var someObj = {
|
||||
propName: "John"
|
||||
};
|
||||
function propPrefix(str) {
|
||||
var s = "prop";
|
||||
return s + str;
|
||||
}
|
||||
var someProp = propPrefix("Name");
|
||||
console.log(someObj[someProp]);
|
||||
```
|
||||
|
||||
`someProp` avrà il valore della stringa `propName` e la stringa `John` sarà visualizzata nella console.
|
||||
|
||||
Nota che *non* usiamo virgolette attorno al nome della variabile quando la usiamo per accedere alla proprietà perché stiamo usando il *valore* della variabile, non il *nome*.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Dai alla variabile `playerNumber` il valore di `16`. Quindi, utilizza la variabile per cercare il nome del giocatore e assegnarla a `player`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`playerNumber` dovrebbe essere un numero
|
||||
|
||||
```js
|
||||
assert(typeof playerNumber === 'number');
|
||||
```
|
||||
|
||||
La variabile `player` dovrebbe essere una stringa
|
||||
|
||||
```js
|
||||
assert(typeof player === 'string');
|
||||
```
|
||||
|
||||
Il valore di `player` dovrebbe essere la stringa `Montana`
|
||||
|
||||
```js
|
||||
assert(player === 'Montana');
|
||||
```
|
||||
|
||||
Dovresti usare la notazione a parentesi per accedere a `testObj`
|
||||
|
||||
```js
|
||||
assert(/testObj\s*?\[.*?\]/.test(code));
|
||||
```
|
||||
|
||||
Non dovresti assegnare direttamente il valore `Montana` alla variabile `player`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/player\s*=\s*"|\'\s*Montana\s*"|\'\s*;/gi));
|
||||
```
|
||||
|
||||
Dovresti usare la variabile `playerNumber` nella notazione a parentesi
|
||||
|
||||
```js
|
||||
assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof player !== "undefined"){(function(v){return v;})(player);}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var testObj = {
|
||||
12: "Namath",
|
||||
16: "Montana",
|
||||
19: "Unitas"
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var playerNumber; // Change this line
|
||||
var player = testObj; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var testObj = {
|
||||
12: "Namath",
|
||||
16: "Montana",
|
||||
19: "Unitas"
|
||||
};
|
||||
var playerNumber = 16;
|
||||
var player = testObj[playerNumber];
|
||||
```
|
@ -0,0 +1,90 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d2
|
||||
title: Aggiungere nuove proprietà a un oggetto JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cQe38UD'
|
||||
forumTopicId: 301169
|
||||
dashedName: add-new-properties-to-a-javascript-object
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Puoi aggiungere nuove proprietà agli oggetti JavaScript esistenti proprio come faresti se volessi modificarli.
|
||||
|
||||
Ecco come aggiungere una proprietà `bark` a `ourDog`:
|
||||
|
||||
```js
|
||||
ourDog.bark = "bow-wow";
|
||||
```
|
||||
|
||||
oppure
|
||||
|
||||
```js
|
||||
ourDog["bark"] = "bow-wow";
|
||||
```
|
||||
|
||||
Ora quando valuteremo `ourDog.bark`, otterremo il suo abbaiare, `bow-wow`.
|
||||
|
||||
Esempio:
|
||||
|
||||
```js
|
||||
var ourDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"]
|
||||
};
|
||||
|
||||
ourDog.bark = "bow-wow";
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Aggiungi una proprietà `bark` a `myDog` e impostala sul suono di un cane, come "woof". È possibile utilizzare sia la notazione a punti che quella a parentesi.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti aggiungere la proprietà `bark` a `myDog`.
|
||||
|
||||
```js
|
||||
assert(myDog.bark !== undefined);
|
||||
```
|
||||
|
||||
Non dovresti aggiungere `bark` all'inizializzazione di `myDog`.
|
||||
|
||||
```js
|
||||
assert(!/bark[^\n]:/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return z;})(myDog);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"]
|
||||
};
|
||||
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"]
|
||||
};
|
||||
myDog.bark = "Woof Woof";
|
||||
```
|
@ -0,0 +1,62 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb3bdef
|
||||
title: Sommare due numeri con JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cM2KBAG'
|
||||
forumTopicId: 16650
|
||||
dashedName: add-two-numbers-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript `Number` è un tipo di dati che rappresenta i dati numerici.
|
||||
|
||||
Ora proviamo a sommare due numeri usando JavaScript.
|
||||
|
||||
JavaScript utilizza il simbolo `+` come operatore di addizione quando è posizionato tra due numeri.
|
||||
|
||||
**Esempio:**
|
||||
|
||||
```js
|
||||
myVar = 5 + 10;
|
||||
```
|
||||
|
||||
`myVar` ora ha il valore `15`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modificare lo `0` in modo che la somma sia uguale a `20`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sum` dovrebbe essere uguale a `20`.
|
||||
|
||||
```js
|
||||
assert(sum === 20);
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `+`.
|
||||
|
||||
```js
|
||||
assert(/\+/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'sum = '+z;})(sum);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var sum = 10 + 0;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var sum = 10 + 10;
|
||||
```
|
@ -0,0 +1,128 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244de
|
||||
title: Aggiungere un'opzione predefinita nelle dichiarazioni Switch
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c3JvVfg'
|
||||
forumTopicId: 16653
|
||||
dashedName: adding-a-default-option-in-switch-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In un'istruzione `switch` potresti non essere in grado di specificare tutti i possibili valori con le dichiarazioni `case`. Puoi invece aggiungere una dichiarazione `default` che verrà eseguita se non vengono trovati `case` corrispondenti. Pensala come l'istruzione `else` finale in una catena `if/else`.
|
||||
|
||||
Un'istruzione `default` dovrebbe essere l'ultimo caso.
|
||||
|
||||
```js
|
||||
switch (num) {
|
||||
case value1:
|
||||
statement1;
|
||||
break;
|
||||
case value2:
|
||||
statement2;
|
||||
break;
|
||||
...
|
||||
default:
|
||||
defaultStatement;
|
||||
break;
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Scrivi un'istruzione switch per impostare `answer` per le seguenti condizioni:
|
||||
`a` - `apple`
|
||||
`b` - `bird`
|
||||
`c` - `cat`
|
||||
`default` - `stuff`
|
||||
|
||||
# --hints--
|
||||
|
||||
`switchOfStuff("a")` dovrebbe restituire la stringa `apple`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('a') === 'apple');
|
||||
```
|
||||
|
||||
`switchOfStuff("b")` dovrebbe restituire la stringa `bird`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('b') === 'bird');
|
||||
```
|
||||
|
||||
`switchOfStuff("c")` dovrebbe restituire la stringa `cat`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('c') === 'cat');
|
||||
```
|
||||
|
||||
`switchOfStuff("d")` dovrebbe restituire la stringa `stuff`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('d') === 'stuff');
|
||||
```
|
||||
|
||||
`switchOfStuff(4)` dovrebbe restituire la stringa `stuff`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff(4) === 'stuff');
|
||||
```
|
||||
|
||||
Non dovresti usare alcuna dichiarazione `if` o `else`
|
||||
|
||||
```js
|
||||
assert(!/else/g.test(code) || !/if/g.test(code));
|
||||
```
|
||||
|
||||
Dovresti usare un'istruzione `default`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('string-to-trigger-default-case') === 'stuff');
|
||||
```
|
||||
|
||||
Dovresti avere almeno altre 3 `break` istruzioni
|
||||
|
||||
```js
|
||||
assert(code.match(/break/g).length > 2);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function switchOfStuff(val) {
|
||||
var answer = "";
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
return answer;
|
||||
}
|
||||
|
||||
switchOfStuff(1);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function switchOfStuff(val) {
|
||||
var answer = "";
|
||||
|
||||
switch(val) {
|
||||
case "a":
|
||||
answer = "apple";
|
||||
break;
|
||||
case "b":
|
||||
answer = "bird";
|
||||
break;
|
||||
case "c":
|
||||
answer = "cat";
|
||||
break;
|
||||
default:
|
||||
answer = "stuff";
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
```
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ed
|
||||
title: Aggiungere variabili alle stringhe
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cbQmZfa'
|
||||
forumTopicId: 16656
|
||||
dashedName: appending-variables-to-strings
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Proprio come possiamo costruire una stringa su più righe di stringhe <dfn>letterali</dfn>, possiamo anche aggiungere delle variabili a una stringa usando l'operatore `+=`.
|
||||
|
||||
Esempio:
|
||||
|
||||
```js
|
||||
var anAdjective = "awesome!";
|
||||
var ourStr = "freeCodeCamp is ";
|
||||
ourStr += anAdjective;
|
||||
```
|
||||
|
||||
`ourStr` avrà il valore `freeCodeCamp is awesome!`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Imposta `someAdjective` a una stringa di almeno 3 caratteri e aggiungila a `myStr` utilizzando l'operatore `+=`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`someAdjective` dovrebbe essere impostato su una stringa lunga almeno 3 caratteri.
|
||||
|
||||
```js
|
||||
assert(typeof someAdjective !== 'undefined' && someAdjective.length > 2);
|
||||
```
|
||||
|
||||
Dovresti aggiungere `someAdjective` a `myStr` usando l'operatore `+=`.
|
||||
|
||||
```js
|
||||
assert(code.match(/myStr\s*\+=\s*someAdjective\s*/).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
var output = [];
|
||||
if(typeof someAdjective === 'string') {
|
||||
output.push('someAdjective = "' + someAdjective + '"');
|
||||
} else {
|
||||
output.push('someAdjective is not a string');
|
||||
}
|
||||
if(typeof myStr === 'string') {
|
||||
output.push('myStr = "' + myStr + '"');
|
||||
} else {
|
||||
output.push('myStr is not a string');
|
||||
}
|
||||
return output.join('\n');
|
||||
})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Change code below this line
|
||||
|
||||
var someAdjective;
|
||||
var myStr = "Learning to code is ";
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var someAdjective = "neat";
|
||||
var myStr = "Learning to code is ";
|
||||
myStr += someAdjective;
|
||||
```
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 5ee127a03c3b35dd45426493
|
||||
title: Assegnare il valore di una variabile ad un'altra
|
||||
challengeType: 1
|
||||
videoUrl: ''
|
||||
forumTopicId: 418265
|
||||
dashedName: assigning-the-value-of-one-variable-to-another
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Dopo che un valore è stato assegnato a una variabile utilizzando l'operatore di <dfn>assegnazione</dfn>, è possibile assegnare il valore di quella variabile ad un'altra utilizzando l'operatore di <dfn>assegnazione</dfn>.
|
||||
|
||||
```js
|
||||
var myVar;
|
||||
myVar = 5;
|
||||
var myNum;
|
||||
myNum = myVar;
|
||||
```
|
||||
|
||||
Questo codice dichiara una variabile `myVar` senza valore, quindi le assegna il valore `5`. Successivamente, una variabile denominata `myNum` viene dichiarata senza un valore. Per finire, il contenuto di `myVar` (che è `5`) viene assegnato alla variabile `myNum`. `myVar` ora ha il valore `5`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Assegna il contenuto di `a` alla variabile `b`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Non dovresti modificare il codice sopra il commento specificato.
|
||||
|
||||
```js
|
||||
assert(/var a;/.test(code) && /a = 7;/.test(code) && /var b;/.test(code));
|
||||
```
|
||||
|
||||
`b` dovrebbe avere un valore di `7`.
|
||||
|
||||
```js
|
||||
assert(typeof b === 'number' && b === 7);
|
||||
```
|
||||
|
||||
`a` dovrebbe essere assegnato a `b` con `=`.
|
||||
|
||||
```js
|
||||
assert(/b\s*=\s*a\s*/g.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
if (typeof a != 'undefined') {
|
||||
a = undefined;
|
||||
}
|
||||
if (typeof b != 'undefined') {
|
||||
b = undefined;
|
||||
}
|
||||
```
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a, b) {
|
||||
return 'a = ' + a + ', b = ' + b;
|
||||
})(a, b);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var a;
|
||||
a = 7;
|
||||
var b;
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a;
|
||||
a = 7;
|
||||
var b;
|
||||
b = a;
|
||||
```
|
@ -0,0 +1,71 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c3
|
||||
title: Assegnazione con un valore restituito
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ce2pEtB'
|
||||
forumTopicId: 16658
|
||||
dashedName: assignment-with-a-returned-value
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Se ricordi la nostra discussione sui [Memorizzare valori con l'operatore di assegnazione](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator), l'espressione a destra del segno uguale viene risolta prima che il valore venga assegnato. Questo significa che possiamo prendere il valore restituito da una funzione e assegnarlo a una variabile.
|
||||
|
||||
Supponiamo di avere predefinito una funzione `sum` che somma due numeri, quindi:
|
||||
|
||||
```js
|
||||
ourSum = sum(5, 12);
|
||||
```
|
||||
|
||||
chiamerà la funzione `sum`, che restituisce un valore di `17`, e lo assegna alla variabile `ourSum`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Chiama la funzione `processArg` con un argomento di `7` e assegna il valore che restituisce alla variabile `processed`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`b` dovrebbe avere un valore di `2`
|
||||
|
||||
```js
|
||||
assert(processed === 2);
|
||||
```
|
||||
|
||||
Dovresti assegnare `processArg` a `processed`
|
||||
|
||||
```js
|
||||
assert(/processed\s*=\s*processArg\(\s*7\s*\)/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){return "processed = " + processed})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var processed = 0;
|
||||
|
||||
function processArg(num) {
|
||||
return (num + 3) / 5;
|
||||
}
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var processed = 0;
|
||||
|
||||
function processArg(num) {
|
||||
return (num + 3) / 5;
|
||||
}
|
||||
|
||||
processed = processArg(7);
|
||||
```
|
@ -0,0 +1,159 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d0
|
||||
title: Costruire oggetti in JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWGkbtd'
|
||||
forumTopicId: 16769
|
||||
dashedName: build-javascript-objects
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Potresti aver già sentito il termine oggetto (`object`).
|
||||
|
||||
Gli oggetti sono simili agli `array`, tranne per il fatto che invece di utilizzare gli indici per accedere e modificare i loro dati, accedi ad essi tramite le cosiddette proprietà (`properties`).
|
||||
|
||||
Gli oggetti sono utili per archiviare i dati in modo strutturato e possono rappresentare oggetti del mondo reale, come un gatto.
|
||||
|
||||
Ecco un esempio di oggetto gatto (cat):
|
||||
|
||||
```js
|
||||
var cat = {
|
||||
"name": "Whiskers",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"enemies": ["Water", "Dogs"]
|
||||
};
|
||||
```
|
||||
|
||||
In questo esempio, tutte le proprietà sono memorizzate come stringhe, come `name`, `legs` e `tails`. Per le proprietà puoi anche usare i numeri. Puoi anche omettere le virgolette per le proprietà di tipo stringa di una sola parola, come segue:
|
||||
|
||||
```js
|
||||
var anotherObject = {
|
||||
make: "Ford",
|
||||
5: "five",
|
||||
"model": "focus"
|
||||
};
|
||||
```
|
||||
|
||||
Tuttavia, se il tuo oggetto ha proprietà non stringa, JavaScript le convertirà automaticamente in stringhe.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Crea un oggetto che rappresenti un cane chiamato `myDog` che contenga le proprietà `name` (una stringa), `legs`, `tails` e `friends`.
|
||||
|
||||
Puoi impostare queste proprietà dell'oggetto sui valori che desideri, purché `name` sia una stringa, `legs` e `tails` siano numeri e `friends` sia un array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myDog` dovrebbe contenere la proprietà `name` ed essa dovrebbe essere una `string`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (z) {
|
||||
if (
|
||||
z.hasOwnProperty('name') &&
|
||||
z.name !== undefined &&
|
||||
typeof z.name === 'string'
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myDog)
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` dovrebbe contenere la proprietà `legs` ed essa dovrebbe essere un `number`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (z) {
|
||||
if (
|
||||
z.hasOwnProperty('legs') &&
|
||||
z.legs !== undefined &&
|
||||
typeof z.legs === 'number'
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myDog)
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` dovrebbe contenere la proprietà `tails` ed essa dovrebbe essere un `number`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (z) {
|
||||
if (
|
||||
z.hasOwnProperty('tails') &&
|
||||
z.tails !== undefined &&
|
||||
typeof z.tails === 'number'
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myDog)
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` dovrebbe contenere la proprietà `friends` ed essa dovrebbe essere un `array`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (z) {
|
||||
if (
|
||||
z.hasOwnProperty('friends') &&
|
||||
z.friends !== undefined &&
|
||||
Array.isArray(z.friends)
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myDog)
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` dovrebbe contenere solo tutte le proprietà indicate.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (z) {
|
||||
return Object.keys(z).length === 4;
|
||||
})(myDog)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return z;})(myDog);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
};
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"]
|
||||
};
|
||||
```
|
@ -0,0 +1,149 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244dc
|
||||
title: Concatenare le istruzioni If Else
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/caeJgsw'
|
||||
forumTopicId: 16772
|
||||
dashedName: chaining-if-else-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Le istruzioni `if/else` possono essere concatenate insieme per dare origine a una logica complessa. Ecco lo <dfn>pseudocode</dfn> di più istruzioni `if` / `else if` concatenate:
|
||||
|
||||
```js
|
||||
if (condition1) {
|
||||
statement1
|
||||
} else if (condition2) {
|
||||
statement2
|
||||
} else if (condition3) {
|
||||
statement3
|
||||
. . .
|
||||
} else {
|
||||
statementN
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Scrivi delle istruzioni `if`/`else if` concatenate per soddisfare le seguenti condizioni:
|
||||
|
||||
`num < 5` - restituisca `Tiny`
|
||||
`num < 10` - restituisca `Small`
|
||||
`num < 15` - restituisca `Medium`
|
||||
`num < 20` - restituisca `Large`
|
||||
`num >= 20` - restituisca `Huge`
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti avere almeno quattro istruzioni `else`
|
||||
|
||||
```js
|
||||
assert(code.match(/else/g).length > 3);
|
||||
```
|
||||
|
||||
Dovresti avere almeno quattro istruzioni `if`
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length > 3);
|
||||
```
|
||||
|
||||
Dovresti avere almeno un'istruzione `return`
|
||||
|
||||
```js
|
||||
assert(code.match(/return/g).length >= 1);
|
||||
```
|
||||
|
||||
`testSize(0)` dovrebbe restituire la stringa `Tiny`
|
||||
|
||||
```js
|
||||
assert(testSize(0) === 'Tiny');
|
||||
```
|
||||
|
||||
`testSize(4)` dovrebbe restituire la stringa `Tiny`
|
||||
|
||||
```js
|
||||
assert(testSize(4) === 'Tiny');
|
||||
```
|
||||
|
||||
`testSize(5)` dovrebbe restituire la stringa `Small`
|
||||
|
||||
```js
|
||||
assert(testSize(5) === 'Small');
|
||||
```
|
||||
|
||||
`testSize(8)` dovrebbe restituire la stringa `Small`
|
||||
|
||||
```js
|
||||
assert(testSize(8) === 'Small');
|
||||
```
|
||||
|
||||
`testSize(10)` dovrebbe restituire la stringa `Medium`
|
||||
|
||||
```js
|
||||
assert(testSize(10) === 'Medium');
|
||||
```
|
||||
|
||||
`testSize(14)` dovrebbe restituire la stringa `Medium`
|
||||
|
||||
```js
|
||||
assert(testSize(14) === 'Medium');
|
||||
```
|
||||
|
||||
`testSize(15)` dovrebbe restituire la stringa `Large`
|
||||
|
||||
```js
|
||||
assert(testSize(15) === 'Large');
|
||||
```
|
||||
|
||||
`testSize(17)` dovrebbe restituire la stringa `Large`
|
||||
|
||||
```js
|
||||
assert(testSize(17) === 'Large');
|
||||
```
|
||||
|
||||
`testSize(20)` dovrebbe restituire la stringa `Huge`
|
||||
|
||||
```js
|
||||
assert(testSize(20) === 'Huge');
|
||||
```
|
||||
|
||||
`testSize(25)` dovrebbe restituire la stringa `Huge`
|
||||
|
||||
```js
|
||||
assert(testSize(25) === 'Huge');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testSize(num) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
return "Change Me";
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
testSize(7);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testSize(num) {
|
||||
if (num < 5) {
|
||||
return "Tiny";
|
||||
} else if (num < 10) {
|
||||
return "Small";
|
||||
} else if (num < 15) {
|
||||
return "Medium";
|
||||
} else if (num < 20) {
|
||||
return "Large";
|
||||
} else {
|
||||
return "Huge";
|
||||
}
|
||||
}
|
||||
```
|
@ -0,0 +1,63 @@
|
||||
---
|
||||
id: bd7123c9c441eddfaeb4bdef
|
||||
title: Commentare il codice JavaScript
|
||||
challengeType: 1
|
||||
removeComments: false
|
||||
videoUrl: 'https://scrimba.com/c/c7ynnTp'
|
||||
forumTopicId: 16783
|
||||
dashedName: comment-your-javascript-code
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
I commenti sono linee di codice che JavaScript ignora intenzionalmente. Essi sono un ottimo modo per lasciare delle note a te stesso e ad altre persone che in seguito avranno bisogno di capire cosa fa quel codice.
|
||||
|
||||
Ci sono due modi per scrivere commenti in JavaScript:
|
||||
|
||||
Usando `//` dirai a JavaScript di ignorare il resto del testo sulla riga corrente. Questo è un commento in linea:
|
||||
|
||||
```js
|
||||
// This is an in-line comment.
|
||||
```
|
||||
|
||||
Puoi fare un commento multi-linea iniziando con `/*` e terminando con `*/`. Questo è un commento multi-linea:
|
||||
|
||||
```js
|
||||
/* This is a
|
||||
multi-line comment */
|
||||
```
|
||||
|
||||
**NOTA:** Quando scrivi codice, dovresti aggiungere regolarmente dei commenti per chiarire la funzione di parti del tuo codice. Un buon commento può aiutare a comunicare l'intento del tuo codice, sia agli altri *che* a te stesso in futuro.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Prova a creare un commento di ogni tipo.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti creare un commento in stile `//` che contenga almeno cinque lettere.
|
||||
|
||||
```js
|
||||
assert(code.match(/(\/\/)...../g));
|
||||
```
|
||||
|
||||
Dovresti creare un commento in stile `/* */` che contenga almeno cinque lettere.
|
||||
|
||||
```js
|
||||
assert(code.match(/(\/\*)([^\/]{5,})(?=\*\/)/gm));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// Fake Comment
|
||||
/* Another Comment */
|
||||
```
|
@ -0,0 +1,91 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d0
|
||||
title: Confrontare con l'operatore di uguaglianza
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cKyVMAL'
|
||||
forumTopicId: 16784
|
||||
dashedName: comparison-with-the-equality-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Ci sono molti <dfn>operatori di confronto</dfn> in JavaScript. Tutti questi operatori restituiscono un valore booleano `true` o `false`.
|
||||
|
||||
L'operatore di base è l'operatore di uguaglianza `==`. L'operatore di uguaglianza confronta due valori e restituisce `true` se sono equivalenti o `false` se non lo sono. Nota che l’uguaglianza è diversa dall’assegnazione (`=`), che assegna il valore che si trova alla destra dell'operatore a una variabile sulla sinistra.
|
||||
|
||||
```js
|
||||
function equalityTest(myVal) {
|
||||
if (myVal == 10) {
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
```
|
||||
|
||||
Se `myVal` è uguale a `10`, l'operatore di uguaglianza restituisce `true`, quindi il codice tra le parentesi graffe sarà eseguito, e la funzione restituirà `Equal`. In caso contrario, la funzione restituirà `Not Equal`. Affinché JavaScript possa confrontare due differenti <dfn>tipi di dato</dfn> (per esempio `numbers` e `strings`), deve convertire un tipo in un altro. Questa operazione è nota come conversione implicita. Dopo che è stata fatta, è possibile confrontare i termini come segue:
|
||||
|
||||
```js
|
||||
1 == 1
|
||||
1 == 2
|
||||
1 == '1'
|
||||
"3" == 3
|
||||
```
|
||||
|
||||
Nell'ordine, queste espressioni saranno valutate come `true`, `false`, `true`, e `true`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Aggiungi l'operatore di uguaglianza alla riga indicata in modo che la funzione restituisca la stringa `Equal` quando `val` è equivalente a `12`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testEqual(10)` dovrebbe restituire la stringa `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testEqual(10) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testEqual(12)` dovrebbe restituire la stringa `Equal`
|
||||
|
||||
```js
|
||||
assert(testEqual(12) === 'Equal');
|
||||
```
|
||||
|
||||
`testEqual("12")` dovrebbe restituire la stringa `Equal`
|
||||
|
||||
```js
|
||||
assert(testEqual('12') === 'Equal');
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `==`
|
||||
|
||||
```js
|
||||
assert(code.match(/==/g) && !code.match(/===/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
|
||||
testEqual(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testEqual(val) {
|
||||
if (val == 12) {
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
```
|
@ -0,0 +1,113 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d4
|
||||
title: Confrontare con l'operatore di maggioranza
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cp6GbH4'
|
||||
forumTopicId: 16786
|
||||
dashedName: comparison-with-the-greater-than-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
L'operatore di maggioranza (`>`) confronta i valori di due numeri. Se il numero a sinistra è maggiore del numero a destra, restituisce `true`. In caso contrario restituisce `false`.
|
||||
|
||||
Come l'operatore di uguaglianza, l'operatore di maggioranza convertirà i tipi di dati dei valori durante il confronto.
|
||||
|
||||
**Esempi**
|
||||
|
||||
```js
|
||||
5 > 3
|
||||
7 > '3'
|
||||
2 > 3
|
||||
'1' > 9
|
||||
```
|
||||
|
||||
Nell'ordine, queste espressioni saranno valutate come `true`, `true`, `false`, e `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Aggiungi l'operatore di maggioranza alle linee indicate in modo che istruzioni return abbiano senso.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testGreaterThan(0)` dovrebbe restituire la stringa `10 or Under`
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(0) === '10 or Under');
|
||||
```
|
||||
|
||||
`testGreaterThan(10)` dovrebbe restituire la stringa `10 or Under`
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(10) === '10 or Under');
|
||||
```
|
||||
|
||||
`testGreaterThan(11)` dovrebbe restituire la stringa `Over 10`
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(11) === 'Over 10');
|
||||
```
|
||||
|
||||
`testGreaterThan(99)` dovrebbe restituire la stringa `Over 10`
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(99) === 'Over 10');
|
||||
```
|
||||
|
||||
`testGreaterThan(100)` deve restituire la stringa `Over 10`
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(100) === 'Over 10');
|
||||
```
|
||||
|
||||
`testGreaterThan(101)` dovrebbe restituire la stringa `Over 100`
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(101) === 'Over 100');
|
||||
```
|
||||
|
||||
`testGreaterThan(150)` dovrebbe restituire la stringa `Over 100`
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(150) === 'Over 100');
|
||||
```
|
||||
|
||||
Dovresti utilizzare l'operatore `>` almeno due volte
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*>\s*('|")*\d+('|")*/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testGreaterThan(val) {
|
||||
if (val) { // Change this line
|
||||
return "Over 100";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "Over 10";
|
||||
}
|
||||
|
||||
return "10 or Under";
|
||||
}
|
||||
|
||||
testGreaterThan(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testGreaterThan(val) {
|
||||
if (val > 100) { // Change this line
|
||||
return "Over 100";
|
||||
}
|
||||
if (val > 10) { // Change this line
|
||||
return "Over 10";
|
||||
}
|
||||
return "10 or Under";
|
||||
}
|
||||
```
|
@ -0,0 +1,115 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d5
|
||||
title: Confronto con l'operatore di maggioranza o uguaglianza
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c6KBqtV'
|
||||
forumTopicId: 16785
|
||||
dashedName: comparison-with-the-greater-than-or-equal-to-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
L'operatore di maggioranza o uguaglianza (`>=`) confronta i valori di due numeri. Se il numero a sinistra è maggiore o uguale al numero a destra, restituisce `true`. In caso contrario, restituisce `false`.
|
||||
|
||||
Come l'operatore di uguaglianza, l'operatore di maggioranza o uguaglianza convertirà i tipi di dati durante il confronto.
|
||||
|
||||
**Esempi**
|
||||
|
||||
```js
|
||||
6 >= 6
|
||||
7 >= '3'
|
||||
2 >= 3
|
||||
'7' >= 9
|
||||
```
|
||||
|
||||
Nell'ordine, queste espressioni saranno valutate `true`, `true`, `false`, e `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Aggiungi l'operatore di maggioranza o uguaglianza alle linee indicate in modo che le istruzioni return abbiano senso.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testGreaterOrEqual(0)` dovrebbe restituire la stringa `less than10`
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(0) === 'Less than 10');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(9)` dovrebbe restituire la stringa `less than 10`
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(9) === 'Less than 10');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(10)` dovrebbe restituire la stringa `10 or Over`
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(10) === '10 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(11)` dovrebbe restituire la stringa `10 or Over`
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(11) === '10 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(19)` dovrebbe restituire la stringa `10 or Over`
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(19) === '10 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(100)` dovrebbe restituire la stringa `20 or Over`
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(100) === '20 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(21)` dovrebbe restituire la stringa `20 or Over`
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(21) === '20 or Over');
|
||||
```
|
||||
|
||||
Dovresti utilizzare l'operatore `>=` almeno due volte
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*>=\s*('|")*\d+('|")*/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testGreaterOrEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "20 or Over";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "10 or Over";
|
||||
}
|
||||
|
||||
return "Less than 10";
|
||||
}
|
||||
|
||||
testGreaterOrEqual(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testGreaterOrEqual(val) {
|
||||
if (val >= 20) { // Change this line
|
||||
return "20 or Over";
|
||||
}
|
||||
|
||||
if (val >= 10) { // Change this line
|
||||
return "10 or Over";
|
||||
}
|
||||
|
||||
return "Less than 10";
|
||||
}
|
||||
```
|
@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d2
|
||||
title: Confrontare con l'operatore di disuguaglianza
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cdBm9Sr'
|
||||
forumTopicId: 16787
|
||||
dashedName: comparison-with-the-inequality-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
L'operatore di disuguaglianza (`!=`) è l'opposto dell'operatore di uguaglianza. Esso significa "non uguale" e restituisce `false` dove l'uguaglianza restituirebbe `true` e *viceversa*. Come l'operatore di uguaglianza, l'operatore di disuguaglianza convertirà i tipi di dati dei valori durante il confronto.
|
||||
|
||||
**Esempi**
|
||||
|
||||
```js
|
||||
1 != 2
|
||||
1 != "1"
|
||||
1 != '1'
|
||||
1 != true
|
||||
0 != false
|
||||
```
|
||||
|
||||
Nell'ordine, queste espressioni saranno valutate `true`, `false`, `false`, `false` e `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Aggiungi l'operatore di disuguaglianza `!=` nell'istruzione `if` in modo che la funzione restituisca la stringa `Not Equal` quando `val` non equivale a `99`
|
||||
|
||||
# --hints--
|
||||
|
||||
`testNotEqual(99)` dovrebbe restituire la stringa `Equal`
|
||||
|
||||
```js
|
||||
assert(testNotEqual(99) === 'Equal');
|
||||
```
|
||||
|
||||
`testNotEqual("99")` dovrebbe restituire la stringa `Equal`
|
||||
|
||||
```js
|
||||
assert(testNotEqual('99') === 'Equal');
|
||||
```
|
||||
|
||||
`testNotEqual(12)` dovrebbe restituire la stringa `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testNotEqual(12) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testNotEqual("12")` dovrebbe restituire la stringa `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testNotEqual('12') === 'Not Equal');
|
||||
```
|
||||
|
||||
`testNotEqual("bob")` dovrebbe restituire la stringa `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testNotEqual('bob') === 'Not Equal');
|
||||
```
|
||||
|
||||
Dovresti utilizzare l'operatore `!=`
|
||||
|
||||
```js
|
||||
assert(code.match(/(?!!==)!=/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testNotEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
|
||||
testNotEqual(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testNotEqual(val) {
|
||||
if (val != 99) {
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
```
|
@ -0,0 +1,108 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d6
|
||||
title: Confronto con l'operatore di minoranza
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNVRWtB'
|
||||
forumTopicId: 16789
|
||||
dashedName: comparison-with-the-less-than-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
L'operatore di minoranza (`<`) confronta i valori di due numeri. Se il numero a sinistra è inferiore al numero a destra, restituisce `true`. In caso contrario, restituisce `false`. Come l'operatore di uguaglianza, l'operatore di minoranza converte i tipi di dati durante il confronto.
|
||||
|
||||
**Esempi**
|
||||
|
||||
```js
|
||||
2 < 5
|
||||
'3' < 7
|
||||
5 < 5
|
||||
3 < 2
|
||||
'8' < 4
|
||||
```
|
||||
|
||||
Nell'ordine, queste espressioni saranno valutate `true`, `true`, `false`, `false`, e `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Aggiungi l'operatore di minoranza alle linee indicate in modo che le istruzioni return abbiano senso.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testLessThan(0)` dovrebbe restituire la stringa `Under 25`
|
||||
|
||||
```js
|
||||
assert(testLessThan(0) === 'Under 25');
|
||||
```
|
||||
|
||||
`testLessThan(24)` dovrebbe restituire la stringa `Under 25`
|
||||
|
||||
```js
|
||||
assert(testLessThan(24) === 'Under 25');
|
||||
```
|
||||
|
||||
`testLessThan(25)` dovrebbe restituire la stringa `Under 55`
|
||||
|
||||
```js
|
||||
assert(testLessThan(25) === 'Under 55');
|
||||
```
|
||||
|
||||
`testLessThan(54)` dovrebbe restituire la stringa `Under 55`
|
||||
|
||||
```js
|
||||
assert(testLessThan(54) === 'Under 55');
|
||||
```
|
||||
|
||||
`testLessThan(55)` dovrebbe restituire la stringa `55 or Over`
|
||||
|
||||
```js
|
||||
assert(testLessThan(55) === '55 or Over');
|
||||
```
|
||||
|
||||
`testLessThan(99)` dovrebbe restituire la stringa `55 or Over`
|
||||
|
||||
```js
|
||||
assert(testLessThan(99) === '55 or Over');
|
||||
```
|
||||
|
||||
Dovresti utilizzare l'operatore `<` almeno due volte
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*<\s*('|")*\d+('|")*/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testLessThan(val) {
|
||||
if (val) { // Change this line
|
||||
return "Under 25";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "Under 55";
|
||||
}
|
||||
|
||||
return "55 or Over";
|
||||
}
|
||||
|
||||
testLessThan(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testLessThan(val) {
|
||||
if (val < 25) { // Change this line
|
||||
return "Under 25";
|
||||
}
|
||||
|
||||
if (val < 55) { // Change this line
|
||||
return "Under 55";
|
||||
}
|
||||
|
||||
return "55 or Over";
|
||||
}
|
||||
```
|
@ -0,0 +1,114 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d7
|
||||
title: Confronto con l'operatore di minoranza o uguaglianza
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNVR7Am'
|
||||
forumTopicId: 16788
|
||||
dashedName: comparison-with-the-less-than-or-equal-to-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
L'operatore di minoranza o uguaglianza (`<=`) confronta i valori di due numeri. Se il numero a sinistra è minore o uguale al numero a destra, restituisce `true`. Se il numero a sinistra è maggiore del numero a destra, restituisce `false`. Come l'operatore di uguaglianza, l'operatore di minoranza o uguaglianza converte i tipi di dati.
|
||||
|
||||
**Esempi**
|
||||
|
||||
```js
|
||||
4 <= 5
|
||||
'7' <= 7
|
||||
5 <= 5
|
||||
3 <= 2
|
||||
'8' <= 4
|
||||
```
|
||||
|
||||
Nell'ordine, queste espressioni saranno valutate `true`, `true`, `true`, `false` e `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Aggiungi l'operatore di minoranza o uguaglianza alle linee indicate in modo che le dichiarazioni return abbiano senso.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testLessOrEqual(0)` dovrebbe restituire la stringa `Smaller Than or Equal to 12`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(0) === 'Smaller Than or Equal to 12');
|
||||
```
|
||||
|
||||
`testLessOrEqual(11)` dovrebbe restituire la stringa `Smaller Than or Equal to 12`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(11) === 'Smaller Than or Equal to 12');
|
||||
```
|
||||
|
||||
`testLessOrEqual(12)` dovrebbe restituire la stringa `Smaller Than or Equal to 12`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(12) === 'Smaller Than or Equal to 12');
|
||||
```
|
||||
|
||||
`testLessOrEqual(23)` dovrebbe restituire la stringa `Smaller Than or Equal to 24`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(23) === 'Smaller Than or Equal to 24');
|
||||
```
|
||||
|
||||
`testLessOrEqual(24)` dovrebbe restituire la stringa `Smaller Than or Equal to 24`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(24) === 'Smaller Than or Equal to 24');
|
||||
```
|
||||
|
||||
`testLessOrEqual(25)` dovrebbe restituire la stringa `more than 24`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(25) === 'More Than 24');
|
||||
```
|
||||
|
||||
`testLessOrEqual(55)` dovrebbe restituire la stringa `More Than 24`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(55) === 'More Than 24');
|
||||
```
|
||||
|
||||
Dovresti utilizzare l'operatore `<=` almeno due volte
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*<=\s*('|")*\d+('|")*/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testLessOrEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "Smaller Than or Equal to 12";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "Smaller Than or Equal to 24";
|
||||
}
|
||||
|
||||
return "More Than 24";
|
||||
}
|
||||
|
||||
testLessOrEqual(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testLessOrEqual(val) {
|
||||
if (val <= 12) { // Change this line
|
||||
return "Smaller Than or Equal to 12";
|
||||
}
|
||||
|
||||
if (val <= 24) { // Change this line
|
||||
return "Smaller Than or Equal to 24";
|
||||
}
|
||||
|
||||
return "More Than 24";
|
||||
}
|
||||
```
|
@ -0,0 +1,82 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d1
|
||||
title: Confronto con l'operatore di uguaglianza stretta
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cy87atr'
|
||||
forumTopicId: 16790
|
||||
dashedName: comparison-with-the-strict-equality-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Uguaglianza stretta (`===`) è la controparte dell'operatore di uguaglianza (`==`). Tuttavia, a differenza dell'operatore di uguaglianza, che cerca di convertire entrambi i valori a un tipo di dato comune per confrontarli, l'operatore di uguaglianza stretta non esegue una conversione di tipo.
|
||||
|
||||
Se i valori confrontati hanno tipi diversi, sono considerati ineguali, e l'operatore di uguaglianza stretta restituirà falso.
|
||||
|
||||
**Esempi**
|
||||
|
||||
```js
|
||||
3 === 3
|
||||
3 === '3'
|
||||
```
|
||||
|
||||
Queste condizioni restituiranno rispettivamente `true` e `false`.
|
||||
|
||||
Nel secondo esempio, `3` è un tipo `Number` e `'3'` è un tipo `String`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa l'operatore di uguaglianza stretta nell'istruzione `if` in modo che la funzione restituisca la stringa `Equal` quando `val` è strettamente uguale a `7`
|
||||
|
||||
# --hints--
|
||||
|
||||
`testStrict(10)` dovrebbe restituire la stringa `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testStrict(10) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testStrict(7)` dovrebbe restituire la stringa `Equal`
|
||||
|
||||
```js
|
||||
assert(testStrict(7) === 'Equal');
|
||||
```
|
||||
|
||||
`testStrict("7")` dovrebbe restituire la stringa `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testStrict('7') === 'Not Equal');
|
||||
```
|
||||
|
||||
È necessario utilizzare l'operatore `===`
|
||||
|
||||
```js
|
||||
assert(code.match(/(val\s*===\s*\d+)|(\d+\s*===\s*val)/g).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testStrict(val) {
|
||||
if (val) { // Change this line
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
|
||||
testStrict(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testStrict(val) {
|
||||
if (val === 7) {
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
```
|
@ -0,0 +1,85 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d3
|
||||
title: Confrontare con l'operatore di disuguaglianza stretta
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cKekkUy'
|
||||
forumTopicId: 16791
|
||||
dashedName: comparison-with-the-strict-inequality-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
L'operatore di disuguaglianza stretta (`!==`) è l'opposto logico dell'operatore di uguaglianza stretta. Significa "strettamente non uguale" e restituisce `false` dove una rigorosa uguaglianza avrebbe restituito `true` e *viceversa*. L'operatore di disuguaglianza stretta non converte i tipi di dati.
|
||||
|
||||
**Esempi**
|
||||
|
||||
```js
|
||||
3 !== 3
|
||||
3 !== '3'
|
||||
4 !== 3
|
||||
```
|
||||
|
||||
Nell'ordine, queste espressioni restituiscono `false`,`true` e `true`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Aggiungi l'operatore di disuguaglianza stretta all'istruzione `if` in modo che la funzione restituisca la stringa `Not Equal` quando `val` non è strettamente uguale a `17`
|
||||
|
||||
# --hints--
|
||||
|
||||
`testStrictNotEqual(17)` dovrebbe restituire la stringa `Equal`
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual(17) === 'Equal');
|
||||
```
|
||||
|
||||
`testStrictNotEqual("17")` dovrebbe restituire la stringa `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual('17') === 'Not Equal');
|
||||
```
|
||||
|
||||
`testStrictNotEqual(12)` dovrebbe restituire la stringa `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual(12) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testStrictNotEqual("bob")` dovrebbe restituire la stringa `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual('bob') === 'Not Equal');
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `!==`
|
||||
|
||||
```js
|
||||
assert(code.match(/(val\s*!==\s*\d+)|(\d+\s*!==\s*val)/g).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testStrictNotEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
|
||||
testStrictNotEqual(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testStrictNotEqual(val) {
|
||||
if (val !== 17) {
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
```
|
@ -0,0 +1,130 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d8
|
||||
title: Confronti con l'operatore logico AND
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cvbRVtr'
|
||||
forumTopicId: 16799
|
||||
dashedName: comparisons-with-the-logical-and-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A volte dovrai testare più di una cosa alla volta. L'operatore logico <dfn>and</dfn> (`&&`) restituisce `true` se e solo se gli <dfn>operandi</dfn> a sinistra e a destra di esso sono veri.
|
||||
|
||||
Lo stesso effetto può essere ottenuto annidando un'istruzione if all'interno di un altro if:
|
||||
|
||||
```js
|
||||
if (num > 5) {
|
||||
if (num < 10) {
|
||||
return "Yes";
|
||||
}
|
||||
}
|
||||
return "No";
|
||||
```
|
||||
|
||||
restituirà `Yes` solo se `num` è maggiore di `5` e minore a `10`. La stessa logica può essere scritta come:
|
||||
|
||||
```js
|
||||
if (num > 5 && num < 10) {
|
||||
return "Yes";
|
||||
}
|
||||
return "No";
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Sostituisci i due if con una sola istruzione, utilizzando l’operatore `&&`, che restituirà la stringa `Yes` se `val` è minore o uguale a `50` e maggiore o uguale a `25`. Altrimenti, restituisci la stringa `No`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti utilizzare l'operatore `&&` una sola volta
|
||||
|
||||
```js
|
||||
assert(code.match(/&&/g).length === 1);
|
||||
```
|
||||
|
||||
Dovresti avere una sola istruzione `if`
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length === 1);
|
||||
```
|
||||
|
||||
`testLogicalAnd(0)` dovrebbe restituire la stringa `No`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(0) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(24)` dovrebbe restituire la stringa `No`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(24) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(25)` dovrebbe restituire la stringa `Yes`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(25) === 'Yes');
|
||||
```
|
||||
|
||||
`testLogicalAnd(30)` dovrebbe restituire la stringa `Yes`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(30) === 'Yes');
|
||||
```
|
||||
|
||||
`testLogicalAnd(50)` dovrebbe restituire la stringa `Yes`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(50) === 'Yes');
|
||||
```
|
||||
|
||||
`testLogicalAnd(51)` dovrebbe restituire la stringa `No`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(51) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(75)` dovrebbe restituire la stringa `No`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(75) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(80)` dovrebbe restituire la stringa `No`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(80) === 'No');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testLogicalAnd(val) {
|
||||
// Only change code below this line
|
||||
|
||||
if (val) {
|
||||
if (val) {
|
||||
return "Yes";
|
||||
}
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
return "No";
|
||||
}
|
||||
|
||||
testLogicalAnd(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testLogicalAnd(val) {
|
||||
if (val >= 25 && val <= 50) {
|
||||
return "Yes";
|
||||
}
|
||||
return "No";
|
||||
}
|
||||
```
|
@ -0,0 +1,135 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d9
|
||||
title: Confronti con l'operatore Or logico
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cEPrGTN'
|
||||
forumTopicId: 16800
|
||||
dashedName: comparisons-with-the-logical-or-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
L'operatore <dfn>Or logico</dfn> (`||`) restituisce `true` se uno degli <dfn>operandi</dfn> è `true`. In caso contrario, restituisce `false`.
|
||||
|
||||
L'operatore <dfn>or logico</dfn> è composto da due simboli "pipe": (`||`). Questo in genere può essere trovato tra i tuoi tasti Backspace e Enter.
|
||||
|
||||
Lo schema sottostante dovrebbe esserti familiare dai punti visti in precedenza:
|
||||
|
||||
```js
|
||||
if (num > 10) {
|
||||
return "No";
|
||||
}
|
||||
if (num < 5) {
|
||||
return "No";
|
||||
}
|
||||
return "Yes";
|
||||
```
|
||||
|
||||
Esso restituirà `Yes` solo se `num` è compreso tra `5` e `10` (5 e 10 inclusi). La stessa logica può essere scritta come:
|
||||
|
||||
```js
|
||||
if (num > 10 || num < 5) {
|
||||
return "No";
|
||||
}
|
||||
return "Yes";
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Combina le due istruzioni `if` in un'unica istruzione che restituisca la stringa `Outside` se `val` non è compreso tra `10` e `20` inclusi. In caso contrario, restituisca la stringa `Inside`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti usare l'operatore `||` una sola volta
|
||||
|
||||
```js
|
||||
assert(code.match(/\|\|/g).length === 1);
|
||||
```
|
||||
|
||||
Dovresti avere una sola istruzione `if`
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length === 1);
|
||||
```
|
||||
|
||||
`testLogicalOr(0)` dovrebbe restituire la stringa `Outside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(0) === 'Outside');
|
||||
```
|
||||
|
||||
`testLogicalOr(9)` dovrebbe restituire la stringa `Outside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(9) === 'Outside');
|
||||
```
|
||||
|
||||
`testLogicalOr(10)` dovrebbe restituire la stringa `Inside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(10) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(15)` dovrebbe restituire la stringa `Inside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(15) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(19)` dovrebbe restituire la stringa `Inside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(19) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(20)` dovrebbe restituire la stringa `Inside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(20) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(21)` dovrebbe restituire la stringa `Outside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(21) === 'Outside');
|
||||
```
|
||||
|
||||
`testLogicalOr(25)` dovrebbe restituire la stringa `Outside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(25) === 'Outside');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testLogicalOr(val) {
|
||||
// Only change code below this line
|
||||
|
||||
if (val) {
|
||||
return "Outside";
|
||||
}
|
||||
|
||||
if (val) {
|
||||
return "Outside";
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
return "Inside";
|
||||
}
|
||||
|
||||
testLogicalOr(15);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testLogicalOr(val) {
|
||||
if (val < 10 || val > 20) {
|
||||
return "Outside";
|
||||
}
|
||||
return "Inside";
|
||||
}
|
||||
```
|
@ -0,0 +1,101 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244af
|
||||
title: Assegnazione composta con addizione aumentata
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDR6LCb'
|
||||
forumTopicId: 16661
|
||||
dashedName: compound-assignment-with-augmented-addition
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Nella programmazione è comune utilizzare le assegnazioni per modificare il contenuto di una variabile. Ricorda che tutto quello che sta alla destra del segno di uguale viene valutato prima, quindi possiamo scrivere:
|
||||
|
||||
```js
|
||||
myVar = myVar + 5;
|
||||
```
|
||||
|
||||
per aggiungere `5` a `myVar`. Poiché questo è uno scherma molto comune, ci sono degli operatori che eseguono sia un'operazione matematica che un'assegnazione in un unico passaggio.
|
||||
|
||||
Uno di questi operatori è l'operatore `+=`.
|
||||
|
||||
```js
|
||||
var myVar = 1;
|
||||
myVar += 5;
|
||||
console.log(myVar);
|
||||
```
|
||||
|
||||
Il valore `6` sarà visualizzato nella console.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Converti le assegnazioni per `a`, `b` e `c` in modo da utilizzare l'operatore `+=`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` dovrebbe essere uguale a `15`.
|
||||
|
||||
```js
|
||||
assert(a === 15);
|
||||
```
|
||||
|
||||
`b` dovrebbe essere uguale a `26`.
|
||||
|
||||
```js
|
||||
assert(b === 26);
|
||||
```
|
||||
|
||||
`c` dovrebbe essere uguale a `19`.
|
||||
|
||||
```js
|
||||
assert(c === 19);
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `+=` per ogni variabile.
|
||||
|
||||
```js
|
||||
assert(code.match(/\+=/g).length === 3);
|
||||
```
|
||||
|
||||
Non dovresti modificare il codice sopra il commento specificato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var a = 3;/.test(code) &&
|
||||
/var b = 17;/.test(code) &&
|
||||
/var c = 12;/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var a = 3;
|
||||
var b = 17;
|
||||
var c = 12;
|
||||
|
||||
// Only change code below this line
|
||||
a = a + 12;
|
||||
b = 9 + b;
|
||||
c = c + 7;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 3;
|
||||
var b = 17;
|
||||
var c = 12;
|
||||
|
||||
a += 12;
|
||||
b += 9;
|
||||
c += 7;
|
||||
```
|
@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b2
|
||||
title: Assegnazione composta con divisione aumentata
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QvKT2'
|
||||
forumTopicId: 16659
|
||||
dashedName: compound-assignment-with-augmented-division
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
L'operatore `/=` divide una variabile per un altro numero.
|
||||
|
||||
```js
|
||||
myVar = myVar / 5;
|
||||
```
|
||||
|
||||
Dividerà `myVar` per `5`. Questo può essere riscritto come:
|
||||
|
||||
```js
|
||||
myVar /= 5;
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Converti le assegnazioni per `a`, `b` e `c` in modo da utilizzare l'operatore `/=`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` dovrebbe essere uguale a `4`.
|
||||
|
||||
```js
|
||||
assert(a === 4);
|
||||
```
|
||||
|
||||
`b` dovrebbe essere uguale a `27`.
|
||||
|
||||
```js
|
||||
assert(b === 27);
|
||||
```
|
||||
|
||||
`c` dovrebbe essere uguale a `3`.
|
||||
|
||||
```js
|
||||
assert(c === 3);
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `/=` per ogni variabile.
|
||||
|
||||
```js
|
||||
assert(code.match(/\/=/g).length === 3);
|
||||
```
|
||||
|
||||
Non dovresti modificare il codice sopra il commento specificato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var a = 48;/.test(code) &&
|
||||
/var b = 108;/.test(code) &&
|
||||
/var c = 33;/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var a = 48;
|
||||
var b = 108;
|
||||
var c = 33;
|
||||
|
||||
// Only change code below this line
|
||||
a = a / 12;
|
||||
b = b / 4;
|
||||
c = c / 11;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 48;
|
||||
var b = 108;
|
||||
var c = 33;
|
||||
|
||||
a /= 12;
|
||||
b /= 4;
|
||||
c /= 11;
|
||||
```
|
@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b1
|
||||
title: Assegnazione composta con moltiplicazione aumentata
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c83vrfa'
|
||||
forumTopicId: 16662
|
||||
dashedName: compound-assignment-with-augmented-multiplication
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
L'operatore `*=` moltiplica una variabile per un numero.
|
||||
|
||||
```js
|
||||
myVar = myVar * 5;
|
||||
```
|
||||
|
||||
moltiplicherà `myVar` per `5`. Questo può essere riscritto come:
|
||||
|
||||
```js
|
||||
myVar *= 5;
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Converti le assegnazioni per `a`, `b` e `c` in modo da utilizzare l'operatore `*=`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` dovrebbe essere uguale a `25`.
|
||||
|
||||
```js
|
||||
assert(a === 25);
|
||||
```
|
||||
|
||||
`b` dovrebbe essere uguale a `36`.
|
||||
|
||||
```js
|
||||
assert(b === 36);
|
||||
```
|
||||
|
||||
`c` dovrebbe essere uguale a `46`.
|
||||
|
||||
```js
|
||||
assert(c === 46);
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `*=` per ogni variabile.
|
||||
|
||||
```js
|
||||
assert(code.match(/\*=/g).length === 3);
|
||||
```
|
||||
|
||||
Non dovresti modificare il codice sopra il commento specificato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var a = 5;/.test(code) &&
|
||||
/var b = 12;/.test(code) &&
|
||||
/var c = 4\.6;/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var a = 5;
|
||||
var b = 12;
|
||||
var c = 4.6;
|
||||
|
||||
// Only change code below this line
|
||||
a = a * 5;
|
||||
b = 3 * b;
|
||||
c = c * 10;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 5;
|
||||
var b = 12;
|
||||
var c = 4.6;
|
||||
|
||||
a *= 5;
|
||||
b *= 3;
|
||||
c *= 10;
|
||||
```
|
@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b0
|
||||
title: Assegnare composta con sottrazione aumentata
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2Qv7AV'
|
||||
forumTopicId: 16660
|
||||
dashedName: compound-assignment-with-augmented-subtraction
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Come l'operatore `+=`, `-=` sottrae un numero da una variabile.
|
||||
|
||||
```js
|
||||
myVar = myVar - 5;
|
||||
```
|
||||
|
||||
sottrarrà `5` da `myVar`. Questo può essere riscritto come:
|
||||
|
||||
```js
|
||||
myVar -= 5;
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Converti le assegnazioni per `a`, `b` e `c` in modo da utilizzare l'operatore `-=`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` dovrebbe essere uguale a `5`.
|
||||
|
||||
```js
|
||||
assert(a === 5);
|
||||
```
|
||||
|
||||
`b` dovrebbe essere uguale a `-6`.
|
||||
|
||||
```js
|
||||
assert(b === -6);
|
||||
```
|
||||
|
||||
`c` dovrebbe essere uguale a `2`.
|
||||
|
||||
```js
|
||||
assert(c === 2);
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `-=` per ogni variabile.
|
||||
|
||||
```js
|
||||
assert(code.match(/-=/g).length === 3);
|
||||
```
|
||||
|
||||
Non dovresti modificare il codice sopra il commento specificato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var a = 11;/.test(code) && /var b = 9;/.test(code) && /var c = 3;/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var a = 11;
|
||||
var b = 9;
|
||||
var c = 3;
|
||||
|
||||
// Only change code below this line
|
||||
a = a - 6;
|
||||
b = b - 15;
|
||||
c = c - 1;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 11;
|
||||
var b = 9;
|
||||
var c = 3;
|
||||
|
||||
a -= 6;
|
||||
b -= 15;
|
||||
c -= 1;
|
||||
```
|
@ -0,0 +1,83 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b7
|
||||
title: Concatenare le stringhe con l'operatore +
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNpM8AN'
|
||||
forumTopicId: 16802
|
||||
dashedName: concatenating-strings-with-plus-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, quando l'operatore `+` viene usato con un valore di tipo `String`, questo prende il nome di operatore di <dfn>concatenazione</dfn>. Puoi costruire una nuova stringa da altre stringhe <dfn>concatenandole</dfn> insieme.
|
||||
|
||||
**Esempio**
|
||||
|
||||
```js
|
||||
'My name is Alan,' + ' I concatenate.'
|
||||
```
|
||||
|
||||
**Nota:** Attenzione agli spazi. La concatenazione non aggiunge spazi tra le stringhe concatenate, quindi dovrai aggiungerli tu stesso.
|
||||
|
||||
Esempio:
|
||||
|
||||
```js
|
||||
var ourStr = "I come first. " + "I come second.";
|
||||
```
|
||||
|
||||
La stringa `I come first. I come second.` sarebbe visualizzata nella console.
|
||||
# --instructions--
|
||||
|
||||
Costruisci `myStr` dalle stringhe `This is the start.` e `This is the end.` usando l'operatore `+`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr` dovrebbe avere un valore stringa `This is the start. This is the end.`
|
||||
|
||||
```js
|
||||
assert(myStr === 'This is the start. This is the end.');
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `+` per costruire `myStr`.
|
||||
|
||||
```js
|
||||
assert(code.match(/(["']).*\1\s*\+\s*(["']).*\2/g));
|
||||
```
|
||||
|
||||
`myStr` dovrebbe essere creato usando la parola chiave `var`.
|
||||
|
||||
```js
|
||||
assert(/var\s+myStr/.test(code));
|
||||
```
|
||||
|
||||
Dovresti assegnare il risultato alla variabile `myStr`.
|
||||
|
||||
```js
|
||||
assert(/myStr\s*=/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
if(typeof myStr === 'string') {
|
||||
return 'myStr = "' + myStr + '"';
|
||||
} else {
|
||||
return 'myStr is not a string';
|
||||
}
|
||||
})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myStr; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "This is the start. " + "This is the end.";
|
||||
```
|
@ -0,0 +1,70 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b8
|
||||
title: Concatenare le stringhe con l'operatore +=
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cbQmmC4'
|
||||
forumTopicId: 16803
|
||||
dashedName: concatenating-strings-with-the-plus-equals-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Possiamo anche usare l'operatore `+=` per <dfn>concatenare</dfn> una stringa alla fine di una variabile stringa esistente. Questo può essere molto utile per rompere una stringa lunga su diverse righe.
|
||||
|
||||
**Nota:** Attenzione agli spazi. La concatenazione non aggiunge spazi tra le stringhe concatenate, quindi dovrai aggiungerli da solo.
|
||||
|
||||
Esempio:
|
||||
|
||||
```js
|
||||
var ourStr = "I come first. ";
|
||||
ourStr += "I come second.";
|
||||
```
|
||||
|
||||
`ourStr` ora ha un valore stringa `I come first. I come second.`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Costruisci `myStr` su diverse righe concatenando queste due stringhe: `This is the first sentence.` e `This is the second sentence.` usando l'operatore `+=`. Usa l'operatore `+=` in modo simile a quello mostrato nell'esempio. Inizia assegnando la prima stringa a `myStr`, quindi aggiungi la seconda.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr` dovrebbe avere un valore stringa `This is the first sentence. This is the second sentence.`
|
||||
|
||||
```js
|
||||
assert(myStr === 'This is the first sentence. This is the second sentence.');
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `+=` per costruire `myStr`.
|
||||
|
||||
```js
|
||||
assert(code.match(/myStr\s*\+=\s*(["']).*\1/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
if(typeof myStr === 'string') {
|
||||
return 'myStr = "' + myStr + '"';
|
||||
} else {
|
||||
return 'myStr is not a string';
|
||||
}
|
||||
})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
|
||||
var myStr;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "This is the first sentence. ";
|
||||
myStr += "This is the second sentence.";
|
||||
```
|
@ -0,0 +1,75 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b9
|
||||
title: Costruire stringhe con le variabili
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cqk8rf4'
|
||||
forumTopicId: 16805
|
||||
dashedName: constructing-strings-with-variables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A volte dovrai costruire una stringa, nello stile di [Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs). Utilizzando l'operatore di concatenazione (`+`), puoi inserire una o più variabili in una stringa che stai costruendo.
|
||||
|
||||
Esempio:
|
||||
|
||||
```js
|
||||
var ourName = "freeCodeCamp";
|
||||
var ourStr = "Hello, our name is " + ourName + ", how are you?";
|
||||
```
|
||||
|
||||
`ourStr` avrà un valore stringa `Hello, our name is freeCodeCamp, how are you?`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Assegna una stringa con valore pari al tuo nome a `myName` e crea `myStr` con `myName` tra le stringhe `My name is` e `and I am well!`
|
||||
|
||||
# --hints--
|
||||
|
||||
`myName` dovrebbe avere il valore di una stringa lunga almeno 3 caratteri.
|
||||
|
||||
```js
|
||||
assert(typeof myName !== 'undefined' && myName.length > 2);
|
||||
```
|
||||
|
||||
Dovresti usare due operatori `+` per costruire `myStr` con `myName` al suo interno.
|
||||
|
||||
```js
|
||||
assert(code.match(/["']\s*\+\s*myName\s*\+\s*["']/g).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
var output = [];
|
||||
if(typeof myName === 'string') {
|
||||
output.push('myName = "' + myName + '"');
|
||||
} else {
|
||||
output.push('myName is not a string');
|
||||
}
|
||||
if(typeof myStr === 'string') {
|
||||
output.push('myStr = "' + myStr + '"');
|
||||
} else {
|
||||
output.push('myStr is not a string');
|
||||
}
|
||||
return output.join('\n');
|
||||
})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
var myName;
|
||||
var myStr;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myName = "Bob";
|
||||
var myStr = "My name is " + myName + " and I am well!";
|
||||
```
|
@ -0,0 +1,75 @@
|
||||
---
|
||||
id: 56105e7b514f539506016a5e
|
||||
title: Contare all'indietro con un ciclo For
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2R6BHa'
|
||||
forumTopicId: 16808
|
||||
dashedName: count-backwards-with-a-for-loop
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Un ciclo for può anche contare all'indietro, se definiamo le condizioni giuste.
|
||||
|
||||
Per decrementare di due ad ogni iterazione, dovremo cambiare la nostra inizializzazione, la condizione e l'espressione finale.
|
||||
|
||||
Inizieremo da `i = 10` e ripeteremo finché `i > 0`. Diminuiremo `i` di 2 ad ogni ciclo con `i -= 2`.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 10; i > 0; i -= 2) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
`ourArray` adesso conterrà `[10,8,6,4,2]`. Cambiamo la nostra inizializzazione e espressione finale in modo da poter contare indietro di due per creare un array di numeri dispari discendenti.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Inserisci i numeri dispari da 9 a 1 in `myArray` usando un ciclo `for`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti usare un ciclo `for` per questo.
|
||||
|
||||
```js
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
Dovresti usare il metodo array `push`.
|
||||
|
||||
```js
|
||||
assert(code.match(/myArray.push/));
|
||||
```
|
||||
|
||||
`myArray` dovrebbe essere uguale a `[9,7,5,3,1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [9, 7, 5, 3, 1]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 9; i > 0; i -= 2) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
@ -0,0 +1,201 @@
|
||||
---
|
||||
id: 565bbe00e9cc8ac0725390f4
|
||||
title: Contare le carte
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c6KE7ty'
|
||||
forumTopicId: 16809
|
||||
dashedName: counting-cards
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Nel gioco di casinò Blackjack, un giocatore può guadagnare un vantaggio rispetto alla casa tenendo traccia del numero relativo di carte alte e basse rimanenti nel mazzo. Questo si chiama [Conteggio delle carte](https://en.wikipedia.org/wiki/Card_counting).
|
||||
|
||||
Avere più carte alte rimanenti nel mazzo favorisce il giocatore. Ad ogni carta è assegnato un valore secondo la tabella sottostante. Quando il conteggio è positivo, il giocatore dovrebbe puntare alto. Quando il conteggio è zero o negativo, il giocatore dovrebbe puntare basso.
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>Cambio del conteggio</th><th>Carte</th></tr></thead><tbody><tr><td>+1</td><td>2, 3, 4, 5, 6</td></tr><tr><td>0</td><td>7, 8, 9</td></tr><tr><td>-1</td><td>10, 'J', 'Q', 'K', 'A'</td></tr></tbody></table>
|
||||
|
||||
Scriverai una funzione che conta le carte. Riceverà un parametro `card`, che può essere un numero o una stringa, e incrementerà o decrementerà la variabile globale `count` in base al valore della carta (vedi tabella). La funzione restituirà una stringa con il conteggio corrente e la stringa `Bet` se il conteggio è positivo, o `Hold` se il conteggio è zero o negativo. Il conteggio corrente e la decisione del giocatore (`Bet` o `Hold`) dovrebbero essere separati da un singolo spazio.
|
||||
|
||||
**Output di esempio:** `-3 Hold` o `5 Bet`
|
||||
|
||||
**Suggerimento**
|
||||
NON resettare `count` a 0 quando il valore è 7, 8 o 9. NON restituire un array.
|
||||
NON includere virgolette (singole o doppie) nell'output.
|
||||
|
||||
# --hints--
|
||||
|
||||
La sequenza di carte 2, 3, 4, 5, 6 dovrebbero restituire `5 Bet`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(2);
|
||||
cc(3);
|
||||
cc(4);
|
||||
cc(5);
|
||||
var out = cc(6);
|
||||
if (out === '5 Bet') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
La sequenza di carte 7, 8, 9 dovrebbe restituire la stringa `0 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(7);
|
||||
cc(8);
|
||||
var out = cc(9);
|
||||
if (out === '0 Hold') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
La sequenza di carte 10, J, Q, K, A dovrebbero restituire la stringa `-5 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(10);
|
||||
cc('J');
|
||||
cc('Q');
|
||||
cc('K');
|
||||
var out = cc('A');
|
||||
if (out === '-5 Hold') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
La sequenza di carte 3, 7, Q, 8, A dovrebbero restituire la stringa `-1 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(3);
|
||||
cc(7);
|
||||
cc('Q');
|
||||
cc(8);
|
||||
var out = cc('A');
|
||||
if (out === '-1 Hold') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
La sequenza di carte 2, J, 9, 2, 7 dovrebbero restituire la stringa `1 Bet`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(2);
|
||||
cc('J');
|
||||
cc(9);
|
||||
cc(2);
|
||||
var out = cc(7);
|
||||
if (out === '1 Bet') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
La sequenza di carte 2, 2, 10 dovrebbero restituire la stringa `1 Bet`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(2);
|
||||
cc(2);
|
||||
var out = cc(10);
|
||||
if (out === '1 Bet') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
La sequenza di carte 3, 2, A, 10, K dovrebbe restituire la stringa `-1 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(3);
|
||||
cc(2);
|
||||
cc('A');
|
||||
cc(10);
|
||||
var out = cc('K');
|
||||
if (out === '-1 Hold') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var count = 0;
|
||||
|
||||
function cc(card) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
return "Change Me";
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
cc(2); cc(3); cc(7); cc('K'); cc('A');
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var count = 0;
|
||||
function cc(card) {
|
||||
switch(card) {
|
||||
case 2:
|
||||
case 3:
|
||||
case 4:
|
||||
case 5:
|
||||
case 6:
|
||||
count++;
|
||||
break;
|
||||
case 10:
|
||||
case 'J':
|
||||
case 'Q':
|
||||
case 'K':
|
||||
case 'A':
|
||||
count--;
|
||||
}
|
||||
if(count > 0) {
|
||||
return count + " Bet";
|
||||
} else {
|
||||
return count + " Hold";
|
||||
}
|
||||
}
|
||||
```
|
@ -0,0 +1,54 @@
|
||||
---
|
||||
id: cf1391c1c11feddfaeb4bdef
|
||||
title: Creare numeri decimali con JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8GEuW'
|
||||
forumTopicId: 16826
|
||||
dashedName: create-decimal-numbers-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Possiamo memorizzare nelle variabili anche i numeri decimali. I numeri decimali a volte sono indicati come numeri <dfn>in virgola mobile (floating point)</dfn> o <dfn>floats</dfn>.
|
||||
|
||||
**Nota:** Non tutti i numeri reali possono essere accuratamente rappresentati in <dfn>floating point</dfn>. Ciò può portare a errori di arrotondamento. [Dettagli qui](https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Crea una variabile `myDecimal` e dalle un valore decimale con una parte frazionaria (es. `5.7`).
|
||||
|
||||
# --hints--
|
||||
|
||||
`myDecimal` dovrebbe essere un numero.
|
||||
|
||||
```js
|
||||
assert(typeof myDecimal === 'number');
|
||||
```
|
||||
|
||||
`myDecimal` dovrebbe avere un punto decimale
|
||||
|
||||
```js
|
||||
assert(myDecimal % 1 != 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){if(typeof myDecimal !== "undefined"){return myDecimal;}})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var ourDecimal = 5.7;
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myDecimal = 9.9;
|
||||
```
|
@ -0,0 +1,61 @@
|
||||
---
|
||||
id: bd7123c9c443eddfaeb5bdef
|
||||
title: Dichiarare le variabili in JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNanrHq'
|
||||
forumTopicId: 17556
|
||||
dashedName: declare-javascript-variables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In informatica, <dfn>i dati</dfn> sono tutto ciò che è significativo per il computer. JavaScript fornisce otto diversi <dfn>tipi di dati</dfn> che sono `undefined`, `null`, `boolean`, `string`, `symbol`, `bigint`, `number` e `object`.
|
||||
|
||||
Per esempio, i computer distinguono tra numeri, come il numero `12`e `strings`, come `"12"`, `"dog"`, o `"123 cats"`, che sono sequenze di caratteri. I computer possono eseguire operazioni matematiche su un numero, ma non su una stringa.
|
||||
|
||||
Le <dfn>variabili</dfn> consentono ai computer di archiviare e manipolare i dati in modo dinamico. Lo fanno utilizzando una "etichetta" per puntare ai dati piuttosto che usare i dati stessi. Ognuno degli otto tipi di dati può essere conservato in una variabile.
|
||||
|
||||
Le variabili sono simili alle variabili x e y che usi nella matematica, cioè sono un nome semplice per rappresentare i dati a cui vogliamo riferirci. Le variabili del computer differiscono dalle variabili matematiche in quanto possono memorizzare valori diversi in momenti diversi.
|
||||
|
||||
Diciamo a JavaScript di creare o <dfn>dichiarare</dfn> una variabile mettendo di fronte la parola chiave `var`, in questo modo:
|
||||
|
||||
```js
|
||||
var ourName;
|
||||
```
|
||||
|
||||
crea una variabile chiamata `ourName`. In JavaScript terminiamo le istruzioni con i punti e virgola. I nomi delle variabili possono essere costituiti da numeri, lettere e `$` o `_`, ma non possono contenere spazi o iniziare con un numero.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa la parola chiave `var` per creare una variabile chiamata `myName`.
|
||||
|
||||
**Suggerimento**
|
||||
Guarda l'esempio `ourName` qui sopra se sei bloccato.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti dichiarare `myName` con la parola chiave `var` terminando con un punto e virgola
|
||||
|
||||
```js
|
||||
assert(/var\s+myName\s*;/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myName !== "undefined"){(function(v){return v;})(myName);}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myName;
|
||||
```
|
@ -0,0 +1,81 @@
|
||||
---
|
||||
id: bd7123c9c444eddfaeb5bdef
|
||||
title: Dichiarare variabili stringa
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QvWU6'
|
||||
forumTopicId: 17557
|
||||
dashedName: declare-string-variables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Precedentemente abbiamo usato il codice
|
||||
|
||||
```js
|
||||
var myName = "your name";
|
||||
```
|
||||
|
||||
`"your name"` è chiamato una <dfn>stringa</dfn> <dfn>letterale</dfn>. È una stringa perché è una serie di zero o più caratteri racchiusi in virgolette singole o doppie.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Crea due nuove variabili stringa: `myFirstName` e `myLastName` e assegna loro i valori rispettivamente del tuo nome e del tuo cognome.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myFirstName` dovrebbe essere una stringa con almeno un carattere al suo interno.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (
|
||||
typeof myFirstName !== 'undefined' &&
|
||||
typeof myFirstName === 'string' &&
|
||||
myFirstName.length > 0
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
`myLastName` dovrebbe essere una stringa con almeno un carattere al suo interno.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (
|
||||
typeof myLastName !== 'undefined' &&
|
||||
typeof myLastName === 'string' &&
|
||||
myLastName.length > 0
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myFirstName !== "undefined" && typeof myLastName !== "undefined"){(function(){return myFirstName + ', ' + myLastName;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myFirstName = "Alan";
|
||||
var myLastName = "Turing";
|
||||
```
|
@ -0,0 +1,80 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ad
|
||||
title: Decrementare un numero con JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cM2KeS2'
|
||||
forumTopicId: 17558
|
||||
dashedName: decrement-a-number-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Puoi facilmente <dfn>decrementare</dfn> o diminuire una variabile con l'operatore `--`.
|
||||
|
||||
```js
|
||||
i--;
|
||||
```
|
||||
|
||||
è equivalente a
|
||||
|
||||
```js
|
||||
i = i - 1;
|
||||
```
|
||||
|
||||
**Nota:** L'intera linea diventa `i--;`, eliminando la necessità di un segno uguale.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Cambia il codice per utilizzare l'operatore `--` su `myVar`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myVar` dovrebbe essere uguale a `10`.
|
||||
|
||||
```js
|
||||
assert(myVar === 10);
|
||||
```
|
||||
|
||||
`myVar = myVar - 1;` dovrebbe essere modificato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var\s*myVar\s*=\s*11;\s*\/*.*\s*([-]{2}\s*myVar|myVar\s*[-]{2});/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `--` su `myVar`.
|
||||
|
||||
```js
|
||||
assert(/[-]{2}\s*myVar|myVar\s*[-]{2}/.test(code));
|
||||
```
|
||||
|
||||
Non dovresti modificare il codice sopra il commento specificato.
|
||||
|
||||
```js
|
||||
assert(/var myVar = 11;/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'myVar = ' + z;})(myVar);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myVar = 11;
|
||||
|
||||
// Only change code below this line
|
||||
myVar = myVar - 1;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myVar = 11;
|
||||
myVar--;
|
||||
```
|
@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d3
|
||||
title: Cancellare le proprietà da un oggetto in JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDqKdTv'
|
||||
forumTopicId: 17560
|
||||
dashedName: delete-properties-from-a-javascript-object
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Possiamo anche cancellare proprietà dagli oggetti in questo modo:
|
||||
|
||||
```js
|
||||
delete ourDog.bark;
|
||||
```
|
||||
|
||||
Esempio:
|
||||
|
||||
```js
|
||||
var ourDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"],
|
||||
"bark": "bow-wow"
|
||||
};
|
||||
|
||||
delete ourDog.bark;
|
||||
```
|
||||
|
||||
Dopo l'ultima riga mostrata sopra, `ourDog` apparirà così:
|
||||
|
||||
```js
|
||||
{
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"]
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Cancella la proprietà `tails` da `myDog`. È possibile utilizzare sia la notazione a punti che quella a parentesi.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti eliminare la proprietà `tails` da `myDog`.
|
||||
|
||||
```js
|
||||
assert(typeof myDog === 'object' && myDog.tails === undefined);
|
||||
```
|
||||
|
||||
Non dovresti modificare il setup di `myDog`.
|
||||
|
||||
```js
|
||||
assert(code.match(/"tails": 1/g).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return z;})(myDog);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"],
|
||||
"bark": "woof"
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"],
|
||||
"bark": "woof"
|
||||
};
|
||||
delete myDog.tails;
|
||||
```
|
@ -0,0 +1,56 @@
|
||||
---
|
||||
id: bd7993c9ca9feddfaeb7bdef
|
||||
title: Dividere un decimale per un altro con JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBZe9AW'
|
||||
forumTopicId: 18255
|
||||
dashedName: divide-one-decimal-by-another-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Ora dividiamo un decimale per un altro.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modifica `0.0` in modo che `quotient` sia uguale a `2.2`.
|
||||
|
||||
# --hints--
|
||||
|
||||
La variabile `quotient` dovrebbe essere uguale a `2.2`
|
||||
|
||||
```js
|
||||
assert(quotient === 2.2);
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `/` per dividere 4.4 per 2
|
||||
|
||||
```js
|
||||
assert(/4\.40*\s*\/\s*2\.*0*/.test(code));
|
||||
```
|
||||
|
||||
La variabile quotient deve essere assegnata solo una volta
|
||||
|
||||
```js
|
||||
assert(code.match(/quotient/g).length === 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y){return 'quotient = '+y;})(quotient);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var quotient = 0.0 / 2.0; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var quotient = 4.4 / 2.0;
|
||||
```
|
@ -0,0 +1,59 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb6bdef
|
||||
title: Dividere un numero per un altro con JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cqkbdAr'
|
||||
forumTopicId: 17566
|
||||
dashedName: divide-one-number-by-another-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Possiamo anche dividere un numero per un altro.
|
||||
|
||||
JavaScript utilizza il simbolo `/` per la divisione.
|
||||
|
||||
**Esempio**
|
||||
|
||||
```js
|
||||
myVar = 16 / 2;
|
||||
```
|
||||
|
||||
`myVar` ora ha il valore `8`.
|
||||
# --instructions--
|
||||
|
||||
Modifica lo `0` in modo che `quotient` sia uguale a `2`.
|
||||
|
||||
# --hints--
|
||||
|
||||
La variabile `quotient` dovrebbe essere uguale a 2.
|
||||
|
||||
```js
|
||||
assert(quotient === 2);
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `/`.
|
||||
|
||||
```js
|
||||
assert(/\d+\s*\/\s*\d+/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'quotient = '+z;})(quotient);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var quotient = 66 / 0;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var quotient = 66 / 33;
|
||||
```
|
@ -0,0 +1,99 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b6
|
||||
title: Sequenze di escape nelle stringhe
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cvmqRh6'
|
||||
forumTopicId: 17567
|
||||
dashedName: escape-sequences-in-strings
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Le virgolette non sono gli unici caratteri dei quali si può fare l'<dfn>escaping</dfn> all'interno di una stringa. Ci sono due motivi per usare i caratteri di escaping:
|
||||
|
||||
1. Per permetterti di utilizzare caratteri che potresti non essere altrimenti in grado di digitare, come ad esempio un ritorno a capo.
|
||||
2. Per permetterti di rappresentare più virgolette in una stringa senza JavaScript interpretare erroneamente ciò che intendi.
|
||||
|
||||
Lo abbiamo imparato nella sfida precedente.
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>Codice</th><th>Output</th></tr></thead><tbody><tr><td><code>\'</code></td><td>virgoletta singola</td></tr><tr><td><code>\"</code></td><td>doppia citazione</td></tr><tr><td><code>\\</code></td><td>barra rovesciata</td></tr><tr><td><code>\n</code></td><td>nuova riga</td></tr><tr><td><code>\r</code></td><td>ritorno a capo</td></tr><tr><td><code>\t</code></td><td>tabulazione</td></tr><tr><td><code>\b</code></td><td>delimitatore di parola</td></tr><tr><td><code>\f</code></td><td>avanzamento carta (form feed)</td></tr></tbody></table>
|
||||
|
||||
*Nota che la barra rovesciata necessita di escaping perché appaia come barra rovesciata.*
|
||||
|
||||
# --instructions--
|
||||
|
||||
Assegna le seguenti tre linee di testo in una sola variabile `myStr` usando le seguenze di escape.
|
||||
|
||||
<blockquote>FirstLine<br> \SecondLine<br>ThirdLine</blockquote>
|
||||
|
||||
Dovrai usare le sequenze di escape per inserire i caratteri speciali. Dovrai seguire anche la spaziatura come sopra, senza spazi tra sequenze di escape o le parole.
|
||||
|
||||
**Note:** L'indentazione per `SecondLine` si ottiene con il carattere di escape di tabulazione, non con gli spazi.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr` non dovrebbe contenere spazi
|
||||
|
||||
```js
|
||||
assert(!/ /.test(myStr));
|
||||
```
|
||||
|
||||
`myStr` dovrebbe contenere le stringhe `FirstLine`, `SecondLine` e `ThirdLine` (ricorda la distinzione tra maiuscole e minuscole)
|
||||
|
||||
```js
|
||||
assert(
|
||||
/FirstLine/.test(myStr) && /SecondLine/.test(myStr) && /ThirdLine/.test(myStr)
|
||||
);
|
||||
```
|
||||
|
||||
`FirstLine` dovrebbe essere seguito dal carattere newline `\n`
|
||||
|
||||
```js
|
||||
assert(/FirstLine\n/.test(myStr));
|
||||
```
|
||||
|
||||
`myStr` dovrebbe contenere un carattere di tabulazione `\t` che segue un carattere nuova riga
|
||||
|
||||
```js
|
||||
assert(/\n\t/.test(myStr));
|
||||
```
|
||||
|
||||
`SecondLine` dovrebbe essere preceduto dal carattere backslash `\`
|
||||
|
||||
```js
|
||||
assert(/\\SecondLine/.test(myStr));
|
||||
```
|
||||
|
||||
Ci dovrebbe essere un carattere nuova riga tra `SecondLine` e `ThirdLine`
|
||||
|
||||
```js
|
||||
assert(/SecondLine\nThirdLine/.test(myStr));
|
||||
```
|
||||
|
||||
`myStr` dovrebbe contenere solo i caratteri mostrati nelle istruzioni
|
||||
|
||||
```js
|
||||
assert(myStr === 'FirstLine\n\t\\SecondLine\nThirdLine');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
if (myStr !== undefined){
|
||||
console.log('myStr:\n' + myStr);}})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myStr; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "FirstLine\n\t\\SecondLine\nThirdLine";
|
||||
```
|
@ -0,0 +1,72 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b5
|
||||
title: Fare l'escaping delle virgolette nelle stringhe
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QvgSr'
|
||||
forumTopicId: 17568
|
||||
dashedName: escaping-literal-quotes-in-strings
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Quando definisci una stringa devi cominciare e finire con una virgoletta singola o doppia. Cosa succede quando ti serve una virgoletta letterale `"` o `'` dentro la tua stringa?
|
||||
|
||||
In JavaScript, puoi fare l'<dfn>escape</dfn> di una virgoletta per distinguerla da quella usata per terminare la stringa posizionando una <dfn>barra rovesciata</dfn> (`\`) davanti alla virgoletta.
|
||||
|
||||
```js
|
||||
var sampleStr = "Alan said, \"Peter is learning JavaScript\".";
|
||||
```
|
||||
|
||||
Questo segnala a JavaScript che la virgoletta seguente non è la fine della stringa, ma dovrebbe invece apparire dentro la stringa. Quindi se dovessi farla visualizzare nella console, otterresti:
|
||||
|
||||
```js
|
||||
Alan said, "Peter is learning JavaScript".
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa le <dfn>barre rovesciate</dfn> per assegnare una stringa alla variabile `myStr` in modo che se dovessi farla visualizzare sulla console, si vedrebbe:
|
||||
|
||||
```js
|
||||
I am a "double quoted" string inside "double quotes".
|
||||
```
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti usare due virgolette doppie (`"`) e quattro virgolette doppie con escape (`\"`).
|
||||
|
||||
```js
|
||||
assert(code.match(/\\"/g).length === 4 && code.match(/[^\\]"/g).length === 2);
|
||||
```
|
||||
|
||||
La variabile myStr dovrebbe contenere la stringa: `I am a "double quoted" string inside "double quotes".`
|
||||
|
||||
```js
|
||||
assert(/I am a "double quoted" string inside "double quotes(\."|"\.)$/.test(myStr));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
if(typeof myStr === 'string') {
|
||||
console.log("myStr = \"" + myStr + "\"");
|
||||
} else {
|
||||
console.log("myStr is undefined");
|
||||
}
|
||||
})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myStr = ""; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "I am a \"double quoted\" string inside \"double quotes\".";
|
||||
```
|
@ -0,0 +1,69 @@
|
||||
---
|
||||
id: bd7123c9c448eddfaeb5bdef
|
||||
title: Trovare la lunghezza di una stringa
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cvmqEAd'
|
||||
forumTopicId: 18182
|
||||
dashedName: find-the-length-of-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Puoi trovare la lunghezza di un valore `String` scrivendo `.length` dopo la variabile stringa o il stringa letterale.
|
||||
|
||||
```js
|
||||
console.log("Alan Peter".length);
|
||||
```
|
||||
|
||||
Il valore `10` sarà visualizzato nella console.
|
||||
|
||||
Ad esempio, se avessimo creato una variabile `var firstName = "Ada"`, potremmo scoprire quanto è lunga la stringa `Ada` utilizzando la proprietà `firstName.length`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa la proprietà `.length` per contare il numero di caratteri nella variabile `lastName` e assegnarla a `lastNameLength`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Non dovresti cambiare le dichiarazioni della variabile nella sezione `// Setup`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(/var lastNameLength = 0;/) &&
|
||||
code.match(/var lastName = "Lovelace";/)
|
||||
);
|
||||
```
|
||||
|
||||
`lastNameLength` dovrebbe essere uguale a 8.
|
||||
|
||||
```js
|
||||
assert(typeof lastNameLength !== 'undefined' && lastNameLength === 8);
|
||||
```
|
||||
|
||||
Dovresti ottenere la lunghezza di `lastName` utilizzando `.length` in questo modo: `lastName.length`.
|
||||
|
||||
```js
|
||||
assert(code.match(/=\s*lastName\.length/g) && !code.match(/lastName\s*=\s*8/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastNameLength = 0;
|
||||
var lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
lastNameLength = lastName;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastNameLength = 0;
|
||||
var lastName = "Lovelace";
|
||||
lastNameLength = lastName.length;
|
||||
```
|
@ -0,0 +1,69 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ae
|
||||
title: Trovare un resto in JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWP24Ub'
|
||||
forumTopicId: 18184
|
||||
dashedName: finding-a-remainder-in-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
L’operatore <dfn>resto</dfn> `%` fornisce il resto della divisione di due numeri.
|
||||
|
||||
**Esempio**
|
||||
|
||||
<blockquote>5 % 2 = 1 perché<br>Math.floor(5 / 2) = 2 (Quoziente)<br>2 * 2 = 4<br>5 - 4 = 1 (Resto)</blockquote>
|
||||
|
||||
**Uso**
|
||||
In matematica si può verificare se un numero è pari o dispari controllando il resto della divisione del numero per `2`.
|
||||
|
||||
<blockquote>17 % 2 = 1 (17 è dispari)<br>48 % 2 = 0 (48 è pari)</blockquote>
|
||||
|
||||
**Nota:** L'operatore <dfn>resto</dfn> è a volte erroneamente indicato come l'operatore del modulo. Esso è molto simile al modulo, ma non funziona correttamente con numeri negativi.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Imposta `remainder` pari al resto di `11` diviso per `3` utilizzando l'operatore <dfn>resto</dfn> (`%`).
|
||||
|
||||
# --hints--
|
||||
|
||||
La variabile `remainder` dovrebbe essere inizializzata
|
||||
|
||||
```js
|
||||
assert(/var\s+?remainder/.test(code));
|
||||
```
|
||||
|
||||
Il valore di `remainder` dovrebbe essere `2`
|
||||
|
||||
```js
|
||||
assert(remainder === 2);
|
||||
```
|
||||
|
||||
Dovresti utilizzare l'operatore `%`
|
||||
|
||||
```js
|
||||
assert(/\s+?remainder\s*?=\s*?.*%.*;?/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y){return 'remainder = '+y;})(remainder);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
|
||||
var remainder;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var remainder = 11 % 3;
|
||||
```
|
@ -0,0 +1,69 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb9bdef
|
||||
title: Generare frazioni casuali con JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cyWJJs3'
|
||||
forumTopicId: 18185
|
||||
dashedName: generate-random-fractions-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
I numeri casuali sono utili per creare comportamenti casuali.
|
||||
|
||||
JavaScript ha una funzione `Math.random()` che genera un numero decimale casuale tra `0` (incluso) e `1` (escluso). Così `Math.random()` può restituire uno `0` ma mai un `1`.
|
||||
|
||||
**Nota:** Come visto in [Memorizzare valori con l'operatore di assegnazione](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator), tutte le chiamate di funzione saranno risolte prima dell'esecuzione del `return`, così possiamo fare un `return` del valore della funzione `Math.random()`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Cambia `randomFraction` per restituire un numero casuale invece di restituire `0`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`randomFraction` dovrebbe restituire un numero casuale.
|
||||
|
||||
```js
|
||||
assert(typeof randomFraction() === 'number');
|
||||
```
|
||||
|
||||
Il numero restituito da `randomFraction` dovrebbe essere un decimale.
|
||||
|
||||
```js
|
||||
assert((randomFraction() + '').match(/\./g));
|
||||
```
|
||||
|
||||
Dovresti usare `Math.random` per generare il numero decimale casuale.
|
||||
|
||||
```js
|
||||
assert(code.match(/Math\.random/g).length >= 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){return randomFraction();})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function randomFraction() {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
return 0;
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function randomFraction() {
|
||||
return Math.random();
|
||||
}
|
||||
```
|
@ -0,0 +1,90 @@
|
||||
---
|
||||
id: cf1111c1c12feddfaeb1bdef
|
||||
title: Generare numeri interi casuali con JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRn6bfr'
|
||||
forumTopicId: 18186
|
||||
dashedName: generate-random-whole-numbers-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
È fantastico poter generare numeri decimali casuali, ma è ancora più utile poter generare numeri interi casuali.
|
||||
|
||||
<ol><li>Utilizza <code>Math.random()</code> per generare un decimale casuale.</li><li>Moltiplica quel decimale casuale per <code>20</code>.</li><li>Usa un'altra funzione, <code>Math.floor()</code> per arrotondare il numero per difetto al numero intero più vicino.</li></ol>
|
||||
|
||||
Ricorda che `Math.random()` non può mai restituire un `1` e, poiché stiamo arrotondando per difetto, è impossibile ottenere effettivamente `20`. Questa tecnica ci darà un numero intero tra `0` e `19`.
|
||||
|
||||
Mettendo tutto insieme, questo è il nostro codice:
|
||||
|
||||
```js
|
||||
Math.floor(Math.random() * 20);
|
||||
```
|
||||
|
||||
Stiamo chiamando `Math.random()`, moltiplicando il risultato per 20, quindi passando il valore alla funzione `Math.floor()` per arrotondare il valore per difetto al numero intero più vicino.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa questa tecnica per generare e restituire un numero intero casuale tra `0` e `9`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Il risultato di `randomWholeNum` dovrebbe essere un numero intero.
|
||||
|
||||
```js
|
||||
assert(
|
||||
typeof randomWholeNum() === 'number' &&
|
||||
(function () {
|
||||
var r = randomWholeNum();
|
||||
return Math.floor(r) === r;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti usare `Math.random` per generare un numero casuale.
|
||||
|
||||
```js
|
||||
assert(code.match(/Math.random/g).length >= 1);
|
||||
```
|
||||
|
||||
Dovresti moltiplicare il risultato di `Math.random` per 10 per renderlo un numero compreso tra zero e nove.
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(/\s*?Math.random\s*?\(\s*?\)\s*?\*\s*?10[\D]\s*?/g) ||
|
||||
code.match(/\s*?10\s*?\*\s*?Math.random\s*?\(\s*?\)\s*?/g)
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti usare `Math.floor` per rimuovere la parte decimale del numero.
|
||||
|
||||
```js
|
||||
assert(code.match(/Math.floor/g).length >= 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){return randomWholeNum();})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function randomWholeNum() {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
return Math.random();
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function randomWholeNum() {
|
||||
return Math.floor(Math.random() * 10);
|
||||
}
|
||||
```
|
@ -0,0 +1,102 @@
|
||||
---
|
||||
id: cf1111c1c12feddfaeb2bdef
|
||||
title: Generare numeri interi casuali all'interno di un intervallo
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cm83yu6'
|
||||
forumTopicId: 18187
|
||||
dashedName: generate-random-whole-numbers-within-a-range
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Invece di generare un numero intero casuale tra zero e un dato numero come abbiamo fatto prima, possiamo generare un numero intero casuale che rientri in un intervallo tra due numeri specifici.
|
||||
|
||||
Per fare questo, definiremo un numero minimo `min` e un numero massimo `max`.
|
||||
|
||||
Ecco la formula che useremo. Prenditi un momento per leggerlo e prova a capire cosa sta facendo questo codice:
|
||||
|
||||
```js
|
||||
Math.floor(Math.random() * (max - min + 1)) + min
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Crea una funzione `randomRange` che prende un intervallo `myMin` e `myMax` e restituisce un numero intero casuale maggiore o uguale di `myMin`, e minore o uguale di `myMax`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Il numero casuale più basso che può essere generato da `randomRange` dovrebbe essere uguale al tuo numero minimo, `myMin`.
|
||||
|
||||
```js
|
||||
assert(calcMin === 5);
|
||||
```
|
||||
|
||||
Il numero casuale più alto che può essere generato da `randomRange` dovrebbe essere uguale al tuo numero massimo, `myMax`.
|
||||
|
||||
```js
|
||||
assert(calcMax === 15);
|
||||
```
|
||||
|
||||
Il numero casuale generato da `randomRange` dovrebbe essere un numero intero, non un decimale.
|
||||
|
||||
```js
|
||||
assert(randomRange(0, 1) % 1 === 0);
|
||||
```
|
||||
|
||||
`randomRange` dovrebbe utilizzare sia `myMax` che `myMin`, e restituire un numero casuale nell'intervallo.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (
|
||||
code.match(/myMax/g).length > 1 &&
|
||||
code.match(/myMin/g).length > 2 &&
|
||||
code.match(/Math.floor/g) &&
|
||||
code.match(/Math.random/g)
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
var calcMin = 100;
|
||||
var calcMax = -100;
|
||||
for(var i = 0; i < 100; i++) {
|
||||
var result = randomRange(5,15);
|
||||
calcMin = Math.min(calcMin, result);
|
||||
calcMax = Math.max(calcMax, result);
|
||||
}
|
||||
(function(){
|
||||
if(typeof myRandom === 'number') {
|
||||
return "myRandom = " + myRandom;
|
||||
} else {
|
||||
return "myRandom undefined";
|
||||
}
|
||||
})()
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function randomRange(myMin, myMax) {
|
||||
// Only change code below this line
|
||||
return 0;
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function randomRange(myMin, myMax) {
|
||||
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
|
||||
}
|
||||
```
|
@ -0,0 +1,128 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244be
|
||||
title: Ambito di applicazione globale e funzioni
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cQM7mCN'
|
||||
forumTopicId: 18193
|
||||
dashedName: global-scope-and-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, lo <dfn>scope</dfn> (campo di applicazione o ambito di visibilità) si riferisce alla visibilità delle variabili. Le variabili che sono definite al di fuori del blocco di una funzione hanno un campo di applicazione <dfn>globale</dfn>. Questo significa che possono essere viste ovunque nel tuo codice JavaScript.
|
||||
|
||||
Le variabili che vengono dichiarate senza la parola chiave `var` vengono create automaticamente nell'ambito `global`. Questo può dare delle conseguenze indesiderate da un'altra parte nel tuo codice o quando si esegue nuovamente la funzione. Dovresti sempre dichiarare le tue variabili con `var`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usando `var`, dichiara una variabile globale denominata `myGlobal` al di fuori di qualsiasi funzione. Inizializzala con un valore di `10`.
|
||||
|
||||
All'interno della funzione `fun1`, assegna `5` a `oopsGlobal` ***senza*** utilizzare la parola chiave `var`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myGlobal` dovrebbe essere definita
|
||||
|
||||
```js
|
||||
assert(typeof myGlobal != 'undefined');
|
||||
```
|
||||
|
||||
`myGlobal` dovrebbe avere un valore di `10`
|
||||
|
||||
```js
|
||||
assert(myGlobal === 10);
|
||||
```
|
||||
|
||||
`myGlobal` dovrebbe essere dichiarata usando la parola chiave `var`
|
||||
|
||||
```js
|
||||
assert(/var\s+myGlobal/.test(code));
|
||||
```
|
||||
|
||||
`oopsGlobal` dovrebbe essere una variabile globale e avere un valore di `5`
|
||||
|
||||
```js
|
||||
assert(typeof oopsGlobal != 'undefined' && oopsGlobal === 5);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
var logOutput = "";
|
||||
var originalConsole = console
|
||||
function capture() {
|
||||
var nativeLog = console.log;
|
||||
console.log = function (message) {
|
||||
logOutput = message;
|
||||
if(nativeLog.apply) {
|
||||
nativeLog.apply(originalConsole, arguments);
|
||||
} else {
|
||||
var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');
|
||||
nativeLog(nativeMsg);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function uncapture() {
|
||||
console.log = originalConsole.log;
|
||||
}
|
||||
var oopsGlobal;
|
||||
capture();
|
||||
```
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
fun1();
|
||||
fun2();
|
||||
uncapture();
|
||||
(function() { return logOutput || "console.log never called"; })();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Declare the myGlobal variable below this line
|
||||
|
||||
|
||||
function fun1() {
|
||||
// Assign 5 to oopsGlobal Here
|
||||
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
function fun2() {
|
||||
var output = "";
|
||||
if (typeof myGlobal != "undefined") {
|
||||
output += "myGlobal: " + myGlobal;
|
||||
}
|
||||
if (typeof oopsGlobal != "undefined") {
|
||||
output += " oopsGlobal: " + oopsGlobal;
|
||||
}
|
||||
console.log(output);
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myGlobal = 10;
|
||||
|
||||
function fun1() {
|
||||
oopsGlobal = 5;
|
||||
}
|
||||
|
||||
function fun2() {
|
||||
var output = "";
|
||||
if(typeof myGlobal != "undefined") {
|
||||
output += "myGlobal: " + myGlobal;
|
||||
}
|
||||
if(typeof oopsGlobal != "undefined") {
|
||||
output += " oopsGlobal: " + oopsGlobal;
|
||||
}
|
||||
console.log(output);
|
||||
}
|
||||
```
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c0
|
||||
title: Ambito globale e ambito locale nelle funzioni
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QwKH2'
|
||||
forumTopicId: 18194
|
||||
dashedName: global-vs--local-scope-in-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
È possibile avere sia variabili <dfn>locali</dfn> che <dfn>globali</dfn> con lo stesso nome. Quando fai questo, la variabile locale ha la precedenza sulla variabile globale.
|
||||
|
||||
In questo esempio:
|
||||
|
||||
```js
|
||||
var someVar = "Hat";
|
||||
function myFun() {
|
||||
var someVar = "Head";
|
||||
return someVar;
|
||||
}
|
||||
```
|
||||
|
||||
La funzione `myFun` restituirà la stringa `Head` perché è presente la versione locale della variabile.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Aggiungi una variabile locale alla funzione `myOutfit` per sovrascrivere il valore di `outerWear` con la stringa `sweater`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Non dovresti cambiare il valore della variabile globale `outerWear`.
|
||||
|
||||
```js
|
||||
assert(outerWear === 'T-Shirt');
|
||||
```
|
||||
|
||||
`myOutfit` dovrebbe restituire la stringa `sweater`.
|
||||
|
||||
```js
|
||||
assert(myOutfit() === 'sweater');
|
||||
```
|
||||
|
||||
Non dovresti cambiare l'istruzione return.
|
||||
|
||||
```js
|
||||
assert(/return outerWear/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var outerWear = "T-Shirt";
|
||||
|
||||
function myOutfit() {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
return outerWear;
|
||||
}
|
||||
|
||||
myOutfit();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var outerWear = "T-Shirt";
|
||||
function myOutfit() {
|
||||
var outerWear = "sweater";
|
||||
return outerWear;
|
||||
}
|
||||
```
|
@ -0,0 +1,135 @@
|
||||
---
|
||||
id: 5664820f61c48e80c9fa476c
|
||||
title: Giocare a golf
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9ykNUR'
|
||||
forumTopicId: 18195
|
||||
dashedName: golf-code
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Nel gioco del [golf](https://en.wikipedia.org/wiki/Golf), ogni buca ha un `par`, che rappresenta il numero medio di `strokes` (colpi) che un golfista dovrebbe fare per mandare la palla in buca per completare il gioco. A seconda di quanto sopra o sotto al valore di `par` sono i tuoi `strokes`, c'è un soprannome diverso.
|
||||
|
||||
Alla tua funzione saranno passati gli argomenti `par` e `strokes`. Restituisci la stringa corretta in base a questa tabella che elenca i colpi in ordine di priorità; dall'alto (maggiore priorità) al basso (minore):
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>Strokes</th><th>Return</th></tr></thead><tbody><tr><td>1</td><td>"Hole-in-one!"</td></tr><tr><td><= par - 2</td><td>"Eagle"</td></tr><tr><td>par - 1</td><td>"Birdie"</td></tr><tr><td>par</td><td>"Par"</td></tr><tr><td>par + 1</td><td>"Bogey"</td></tr><tr><td>par + 2</td><td>"Double Bogey"</td></tr><tr><td>>= par + 3</td><td>"Go Home!"</td></tr></tbody></table>
|
||||
|
||||
`par` e `strokes` avranno sempre valori numerici e positivi. Abbiamo aggiunto un array con tutti i nomi per tua comodità.
|
||||
|
||||
# --hints--
|
||||
|
||||
`golfScore(4, 1)` dovrebbe restituire la stringa `Hole-in-one!`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 1) === 'Hole-in-one!');
|
||||
```
|
||||
|
||||
`golfScore(4, 2)` dovrebbe restituire la stringa `Eagle`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 2) === 'Eagle');
|
||||
```
|
||||
|
||||
`golfScore(5, 2)` dovrebbe restituire la stringa `Eagle`
|
||||
|
||||
```js
|
||||
assert(golfScore(5, 2) === 'Eagle');
|
||||
```
|
||||
|
||||
`golfScore(4, 3)` dovrebbe restituire la stringa `Birdie`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 3) === 'Birdie');
|
||||
```
|
||||
|
||||
`golfScore(4, 4)` dovrebbe restituire la stringa `Par`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 4) === 'Par');
|
||||
```
|
||||
|
||||
`golfScore(1, 1)` dovrebbe restituire la stringa `Hole-in-one!`
|
||||
|
||||
```js
|
||||
assert(golfScore(1, 1) === 'Hole-in-one!');
|
||||
```
|
||||
|
||||
`golfScore(5, 5)` dovrebbe restituire la stringa `Par`
|
||||
|
||||
```js
|
||||
assert(golfScore(5, 5) === 'Par');
|
||||
```
|
||||
|
||||
`golfScore(4, 5)` dovrebbe restituire la stringa `Bogey`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 5) === 'Bogey');
|
||||
```
|
||||
|
||||
`golfScore(4, 6)` dovrebbe restituire la stringa `Double Bogey`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 6) === 'Double Bogey');
|
||||
```
|
||||
|
||||
`golfScore(4, 7)` dovrebbe restituire la stringa `Go Home!`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 7) === 'Go Home!');
|
||||
```
|
||||
|
||||
`golfScore(5, 9)` dovrebbe restituire la stringa `Go Home!`
|
||||
|
||||
```js
|
||||
assert(golfScore(5, 9) === 'Go Home!');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
|
||||
function golfScore(par, strokes) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
return "Change Me";
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
golfScore(5, 4);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function golfScore(par, strokes) {
|
||||
if (strokes === 1) {
|
||||
return "Hole-in-one!";
|
||||
}
|
||||
|
||||
if (strokes <= par - 2) {
|
||||
return "Eagle";
|
||||
}
|
||||
|
||||
if (strokes === par - 1) {
|
||||
return "Birdie";
|
||||
}
|
||||
|
||||
if (strokes === par) {
|
||||
return "Par";
|
||||
}
|
||||
|
||||
if (strokes === par + 1) {
|
||||
return "Bogey";
|
||||
}
|
||||
|
||||
if(strokes === par + 2) {
|
||||
return "Double Bogey";
|
||||
}
|
||||
|
||||
return "Go Home!";
|
||||
}
|
||||
```
|
@ -0,0 +1,80 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ac
|
||||
title: Incrementare un numero con JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8GLT9'
|
||||
forumTopicId: 18201
|
||||
dashedName: increment-a-number-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Puoi facilmente <dfn>incrementare</dfn> o aggiungerne un'unità a una variabile con l'operatore `++`.
|
||||
|
||||
```js
|
||||
i++;
|
||||
```
|
||||
|
||||
è l'equivalente di
|
||||
|
||||
```js
|
||||
i = i + 1;
|
||||
```
|
||||
|
||||
**Nota:** L'intera linea diventa `i++;`, eliminando la necessità di un segno uguale.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Cambia il codice per utilizzare l'operatore `++` su `myVar`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myVar` dovrebbe essere uguale a `88`.
|
||||
|
||||
```js
|
||||
assert(myVar === 88);
|
||||
```
|
||||
|
||||
Non dovresti utilizzare l'operatore di assegnazione.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var\s*myVar\s*=\s*87;\s*\/*.*\s*([+]{2}\s*myVar|myVar\s*[+]{2});/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `++`.
|
||||
|
||||
```js
|
||||
assert(/[+]{2}\s*myVar|myVar\s*[+]{2}/.test(code));
|
||||
```
|
||||
|
||||
Non dovresti cambiare il codice sopra il commento specificato.
|
||||
|
||||
```js
|
||||
assert(/var myVar = 87;/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'myVar = ' + z;})(myVar);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myVar = 87;
|
||||
|
||||
// Only change code below this line
|
||||
myVar = myVar + 1;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myVar = 87;
|
||||
myVar++;
|
||||
```
|
@ -0,0 +1,50 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244a9
|
||||
title: Inizializzare le variabili con l'operatore di assegnazione
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWJ4Bfb'
|
||||
forumTopicId: 301171
|
||||
dashedName: initializing-variables-with-the-assignment-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
È comune <dfn>inizializzare</dfn> una variabile ad un valore iniziale nella stessa riga in cui viene dichiarata.
|
||||
|
||||
```js
|
||||
var myVar = 0;
|
||||
```
|
||||
|
||||
Crea una nuova variabile chiamata `myVar` e assegna ad essa un valore iniziale di `0`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Definisci una variabile `a` con `var` e inizializzala ad un valore di `9`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti inizializzare `a` ad un valore di `9`.
|
||||
|
||||
```js
|
||||
assert(/var\s+a\s*=\s*9(\s*;?\s*)$/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof a !== 'undefined') {(function(a){return "a = " + a;})(a);} else { (function() {return 'a is undefined';})(); }
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 9;
|
||||
```
|
@ -0,0 +1,114 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244db
|
||||
title: Introduzione alle istruzioni Else If
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/caeJ2hm'
|
||||
forumTopicId: 18206
|
||||
dashedName: introducing-else-if-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Se hai più condizioni che devono essere valutate, puoi concatenare le istruzioni `if` con le istruzioni `else if`.
|
||||
|
||||
```js
|
||||
if (num > 15) {
|
||||
return "Bigger than 15";
|
||||
} else if (num < 5) {
|
||||
return "Smaller than 5";
|
||||
} else {
|
||||
return "Between 5 and 15";
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Converti la logica per usare le istruzioni `else if`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti avere almeno due istruzioni `else`
|
||||
|
||||
```js
|
||||
assert(code.match(/else/g).length > 1);
|
||||
```
|
||||
|
||||
Dovresti avere almeno due istruzioni `if`
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length > 1);
|
||||
```
|
||||
|
||||
Dovresti avere una parentesi graffa di apertura e una di chiusura per ogni blocco di codice `if else`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(
|
||||
/if\s*\((.+)\)\s*\{[\s\S]+\}\s*else\s+if\s*\((.+)\)\s*\{[\s\S]+\}\s*else\s*\{[\s\S]+\s*\}/
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
`testElseIf(0)` dovrebbe restituire la stringa `Smaller than 5`
|
||||
|
||||
```js
|
||||
assert(testElseIf(0) === 'Smaller than 5');
|
||||
```
|
||||
|
||||
`testElseIf(5)` dovrebbe restituire la stringa `Between 5 and 10`
|
||||
|
||||
```js
|
||||
assert(testElseIf(5) === 'Between 5 and 10');
|
||||
```
|
||||
|
||||
`testElseIf(7)` dovrebbe restituire la stringa `Between 5 and 10`
|
||||
|
||||
```js
|
||||
assert(testElseIf(7) === 'Between 5 and 10');
|
||||
```
|
||||
|
||||
`testElseIf(10)` dovrebbe restituire la stringa `Between 5 and 10`
|
||||
|
||||
```js
|
||||
assert(testElseIf(10) === 'Between 5 and 10');
|
||||
```
|
||||
|
||||
`testElseIf(12)` dovrebbe restituire la stringa `Greater than 10`
|
||||
|
||||
```js
|
||||
assert(testElseIf(12) === 'Greater than 10');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testElseIf(val) {
|
||||
if (val > 10) {
|
||||
return "Greater than 10";
|
||||
}
|
||||
|
||||
if (val < 5) {
|
||||
return "Smaller than 5";
|
||||
}
|
||||
|
||||
return "Between 5 and 10";
|
||||
}
|
||||
|
||||
testElseIf(7);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testElseIf(val) {
|
||||
if(val > 10) {
|
||||
return "Greater than 10";
|
||||
} else if(val < 5) {
|
||||
return "Smaller than 5";
|
||||
} else {
|
||||
return "Between 5 and 10";
|
||||
}
|
||||
}
|
||||
```
|
@ -0,0 +1,106 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244da
|
||||
title: Introduzione alle dichiarazioni Else
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cek4Efq'
|
||||
forumTopicId: 18207
|
||||
dashedName: introducing-else-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Quando una condizione per un'istruzione `if` è vera, viene eseguito il blocco di codice che segue. E quando quella condizione è falsa? Di solito non succede niente. Con un'istruzione `else` è possibile eseguire un blocco di codice alternativo.
|
||||
|
||||
```js
|
||||
if (num > 10) {
|
||||
return "Bigger than 10";
|
||||
} else {
|
||||
return "10 or Less";
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Combina le istruzioni `if` in una singola istruzione `if/else`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti avere una sola istruzione `if` nell'editor
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length === 1);
|
||||
```
|
||||
|
||||
Dovresti usare una istruzione `else`
|
||||
|
||||
```js
|
||||
assert(/else/g.test(code));
|
||||
```
|
||||
|
||||
`testElse(4)` dovrebbe restituire la stringa `5 or Smaller`
|
||||
|
||||
```js
|
||||
assert(testElse(4) === '5 or Smaller');
|
||||
```
|
||||
|
||||
`testElse(5)` dovrebbe restituire la stringa `5 or Smaller`
|
||||
|
||||
```js
|
||||
assert(testElse(5) === '5 or Smaller');
|
||||
```
|
||||
|
||||
`testElse(6)` dovrebbe restituire la stringa `Bigger than 5`
|
||||
|
||||
```js
|
||||
assert(testElse(6) === 'Bigger than 5');
|
||||
```
|
||||
|
||||
`testElse(10)` dovrebbe restituire la stringa `Bigger than 5`
|
||||
|
||||
```js
|
||||
assert(testElse(10) === 'Bigger than 5');
|
||||
```
|
||||
|
||||
Non dovresti modificare il codice sopra o sotto i commenti specificati.
|
||||
|
||||
```js
|
||||
assert(/var result = "";/.test(code) && /return result;/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testElse(val) {
|
||||
var result = "";
|
||||
// Only change code below this line
|
||||
|
||||
if (val > 5) {
|
||||
result = "Bigger than 5";
|
||||
}
|
||||
|
||||
if (val <= 5) {
|
||||
result = "5 or Smaller";
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
return result;
|
||||
}
|
||||
|
||||
testElse(4);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testElse(val) {
|
||||
var result = "";
|
||||
if(val > 5) {
|
||||
result = "Bigger than 5";
|
||||
} else {
|
||||
result = "5 or Smaller";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
```
|
@ -0,0 +1,67 @@
|
||||
---
|
||||
id: 56104e9e514f539506016a5c
|
||||
title: Iterare numeri dispari con un ciclo for
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cm8n7T9'
|
||||
forumTopicId: 18212
|
||||
dashedName: iterate-odd-numbers-with-a-for-loop
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
I cicli for non devono necessariamente iterare un numero alla volta. Modificando la nostra `final-expression` possiamo iterare solo sui numeri pari.
|
||||
|
||||
Inizieremo da `i = 0` e ripeteremo il ciclo finché `i < 10`. Incrementeremo `i` di 2 ad ogni ciclo con `i += 2`.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 0; i < 10; i += 2) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
`ourArray` ora conterrà `[0,2,4,6,8]`. Cambiamo la nostra `initialization` in modo da poter iterare sui numeri dispari.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Inserisci i numeri dispari da 1 a 9 in `myArray` usando un ciclo `for`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti usare un ciclo `for`.
|
||||
|
||||
```js
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
`myArray` dovrebbe essere uguale a `[1,3,5,7,9]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [1, 3, 5, 7, 9]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 1; i < 10; i += 2) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
@ -0,0 +1,79 @@
|
||||
---
|
||||
id: 5675e877dbd60be8ad28edc6
|
||||
title: Iterare attraverso un array con un ciclo For
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/caeR3HB'
|
||||
forumTopicId: 18216
|
||||
dashedName: iterate-through-an-array-with-a-for-loop
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Un compito comune in JavaScript è quello di iterare attraverso i contenuti di un array. Un modo per farlo è con un ciclo `for`. Questo codice visualizzerà ogni elemento dell'array `arr` nella console:
|
||||
|
||||
```js
|
||||
var arr = [10, 9, 8, 7, 6];
|
||||
for (var i = 0; i < arr.length; i++) {
|
||||
console.log(arr[i]);
|
||||
}
|
||||
```
|
||||
|
||||
Ricorda che gli array hanno un'indicizzazione basata sullo zero, il che significa che l'ultimo indice dell'array è `length - 1`. La nostra condizione per questo ciclo è `i < arr.length` che interrompe il ciclo quando `i` è uguale a `length`. In questo caso l’ultima iterazione è `i === 4` i.e. quando `i` diventa uguale a `arr.length - 1` e `6` viene visualizzato nella la console. Quindi `i` diventa `5`, e il ciclo termina perché `i < arr.length` è uguale a `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Dichiara una variabile `total` e inizializzala a `0`. Usa un ciclo `for` per sommare il valore di ogni elemento dell'array `myArr` a `total`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`total` dovrebbe essere dichiarato e inizializzato a 0.
|
||||
|
||||
```js
|
||||
assert(code.match(/(var|let|const)\s*?total\s*=\s*0.*?;?/));
|
||||
```
|
||||
|
||||
`total` dovrebbe essere uguale a 20.
|
||||
|
||||
```js
|
||||
assert(total === 20);
|
||||
```
|
||||
|
||||
Dovresti usare un ciclo `for` per iterare attraverso `myArr`.
|
||||
|
||||
```js
|
||||
assert(/for\s*\(/g.test(code) && /myArr\s*\[/g.test(code));
|
||||
```
|
||||
|
||||
Non dovresti tentare di assegnare direttamente il valore 20 a `total`.
|
||||
|
||||
```js
|
||||
assert(!__helpers.removeWhiteSpace(code).match(/total[=+-]0*[1-9]+/gm));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){if(typeof total !== 'undefined') { return "total = " + total; } else { return "total is undefined";}})()
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArr = [ 2, 3, 4, 5, 6];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArr = [ 2, 3, 4, 5, 6];
|
||||
var total = 0;
|
||||
|
||||
for (var i = 0; i < myArr.length; i++) {
|
||||
total += myArr[i];
|
||||
}
|
||||
```
|
@ -0,0 +1,102 @@
|
||||
---
|
||||
id: 5a2efd662fb457916e1fe604
|
||||
title: Iterare con i cicli Do...While in Javascript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDqWGcp'
|
||||
forumTopicId: 301172
|
||||
dashedName: iterate-with-javascript-do---while-loops
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Il prossimo tipo di ciclo che vedremo si chiama `do...while`. Si chiama ciclo `do... while` perché prima eseguirà (`do`) un passaggio del codice all'interno del ciclo indipendentemente dalle condizioni, e poi continuerà ad eseguire il ciclo finché (`while`) la condizione specificata avrà valore `true`.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
var i = 0;
|
||||
do {
|
||||
ourArray.push(i);
|
||||
i++;
|
||||
} while (i < 5);
|
||||
```
|
||||
|
||||
L'esempio sopra si comporta come altri tipi di cicli, e l'array risultante sarà `[0, 1, 2, 3, 4]`. Tuttavia, ciò che rende il `do...while` diverso da altri cicli è come si comporta quando la condizione fallisce al primo controllo. Vediamolo in azione: ecco un normale ciclo `while` che eseguirà il codice nel ciclo finché `i < 5`:
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
var i = 5;
|
||||
while (i < 5) {
|
||||
ourArray.push(i);
|
||||
i++;
|
||||
}
|
||||
```
|
||||
|
||||
In questo esempio, inizializziamo il valore di `ourArray` a un array vuoto e il valore di `i` a 5. Quando eseguiamo il ciclo `while`, la condizione vale `false` perché `i` non è inferiore a 5, e in questo modo non eseguiremo il codice all'interno del ciclo. Il risultato è che `ourArray` finirà per non avere valori aggiunti, e sarà ancora simile a `[]` quando tutto il codice nell'esempio precedente sarà stato completato. Ora, dai un'occhiata a un ciclo `do...while`:
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
var i = 5;
|
||||
do {
|
||||
ourArray.push(i);
|
||||
i++;
|
||||
} while (i < 5);
|
||||
```
|
||||
|
||||
In questo caso, inizializziamo il valore di `i` a 5, proprio come abbiamo fatto con il ciclo `while`. Quando arriviamo alla linea successiva, non c'è alcuna condizione da valutare, così passiamo al codice all'interno delle parentesi graffe e lo eseguiamo. Aggiungeremo un singolo elemento all'array e quindi incrementeremo `i` prima di arrivare al controllo delle condizioni. Quando finalmente valutiamo la condizione `i < 5` sull'ultima riga, vediamo che `i` è ora 6, che fallisce il controllo condizionale, quindi usciamo dal ciclo e terminiamo l'esecuzione. Alla fine dell'esempio visto sopra, il valore di `ourArray` è `[5]`. Essenzialmente, un ciclo `do...while` assicura che il codice all'interno del ciclo venga eseguito almeno una volta. Proviamo ad ottenere un ciclo `do...while` che ci permetta di inserire dei valori in un array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Cambia il ciclo `while` nel codice con un ciclo `do...while` in modo che il ciclo inserisca solo il numero `10` in `myArray`, e `i` sia uguale a `11` una volta che il codice sarà terminato.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti usare un ciclo `do...while` per questo esercizio.
|
||||
|
||||
```js
|
||||
assert(code.match(/do/g));
|
||||
```
|
||||
|
||||
`myArray` dovrebbe essere uguale a `[10]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [10]);
|
||||
```
|
||||
|
||||
`i` dovrebbe essere uguale a `11`
|
||||
|
||||
```js
|
||||
assert.equal(i, 11);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
var i = 10;
|
||||
|
||||
// Only change code below this line
|
||||
while (i < 5) {
|
||||
myArray.push(i);
|
||||
i++;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
var i = 10;
|
||||
do {
|
||||
myArray.push(i);
|
||||
i++;
|
||||
} while (i < 5)
|
||||
```
|
@ -0,0 +1,79 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb5bdef
|
||||
title: Iterare con i cicli For in Javascript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9yNVCe'
|
||||
forumTopicId: 18219
|
||||
dashedName: iterate-with-javascript-for-loops
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
È possibile eseguire lo stesso codice più volte utilizzando un ciclo.
|
||||
|
||||
Il tipo più comune di ciclo JavaScript è chiamato un ciclo `for` perché esso viene eseguito per ("for") un numero specifico di volte.
|
||||
|
||||
I cicli For sono dichiarati con tre espressioni facoltative separate da punti e virgola:
|
||||
|
||||
`for (a; b; c)`, dove `a` è l'istruzione di inizializzazione, `b` è la condizione, e `c` è l'espressione finale.
|
||||
|
||||
L'istruzione di inizializzazione viene eseguita una sola volta prima dell'inizio del ciclo. È tipicamente usata per definire e configurare la variabile del ciclo.
|
||||
|
||||
La condizione viene valutata all'inizio di ogni iterazione del ciclo, e continuerà finché essa vale `true`. Quando la condizione è `false` all'inizio dell'iterazione, il ciclo terminerà l'esecuzione. Ciò significa che se la condizione inizia come false, il tuo ciclo non verrà mai eseguito.
|
||||
|
||||
L'espressione finale è eseguita alla fine di ogni iterazione del ciclo, prima del prossimo controllo delle condizioni e di solito viene utilizzata per aumentare o diminuire il contatore del ciclo.
|
||||
|
||||
Nell'esempio seguente inizializziamo con `i = 0` e iteriamo finché la nostra condizione `i < 5` è vera. Incrementeremo `i` di `1` ad ogni iterazione del ciclo con `i++` come espressione finale.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 0; i < 5; i++) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
`ourArray` ha ora il valore `[0,1,2,3,4]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa un ciclo `for` per inserire i valori da 1 a 5 in `myArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti usare un ciclo `for`.
|
||||
|
||||
```js
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
`myArray` dovrebbe essere uguale a `[1,2,3,4,5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [1, 2, 3, 4, 5]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if (typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 1; i < 6; i++) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
@ -0,0 +1,73 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb1bdef
|
||||
title: Iterare con il ciclo While in Javascript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c8QbnCM'
|
||||
forumTopicId: 18220
|
||||
dashedName: iterate-with-javascript-while-loops
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
È possibile eseguire lo stesso codice più volte utilizzando un ciclo.
|
||||
|
||||
Il primo tipo di ciclo che vedremo è chiamato un ciclo `while` perché viene eseguito finché (while) una condizione specificata è vera e si arresta una volta che la condizione non è più vera.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
var i = 0;
|
||||
while(i < 5) {
|
||||
ourArray.push(i);
|
||||
i++;
|
||||
}
|
||||
```
|
||||
|
||||
Nell'esempio di codice precedente, il ciclo `while` sarà eseguito 5 volte e aggiungerà i numeri da 0 a 4 a `ourArray`.
|
||||
|
||||
Proviamo ad realizzare un ciclo che inserisca i valori in un array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Aggiungi i numeri da 5 a 0 (inclusi) in ordine decrescente a `myArray` utilizzando un ciclo `while`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti usare un ciclo `while`.
|
||||
|
||||
```js
|
||||
assert(code.match(/while/g));
|
||||
```
|
||||
|
||||
`myArray` dovrebbe essere uguale a `[5,4,3,2,1,0]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [5, 4, 3, 2, 1, 0]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
var i = 5;
|
||||
while(i >= 0) {
|
||||
myArray.push(i);
|
||||
i--;
|
||||
}
|
||||
```
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244bf
|
||||
title: Ambito locale e funzioni
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cd62NhM'
|
||||
forumTopicId: 18227
|
||||
dashedName: local-scope-and-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Le variabili che sono dichiarate all'interno di una funzione, così come i parametri della funzione, hanno un ambito di applicazione (scope) <dfn>locale</dfn>. Ciò significa che sono visibili solo all'interno di quella funzione.
|
||||
|
||||
Ecco una funzione `myTest` con una variabile locale chiamata `loc`.
|
||||
|
||||
```js
|
||||
function myTest() {
|
||||
var loc = "foo";
|
||||
console.log(loc);
|
||||
}
|
||||
myTest();
|
||||
console.log(loc);
|
||||
```
|
||||
|
||||
La chiamata alla funzione `myTest()` mostrerà la stringa `foo` nella console. La linea `console.log(loc)` genererà un errore, perché `loc` non è definita al di fuori della funzione.
|
||||
|
||||
# --instructions--
|
||||
|
||||
L'editor ha due `console.log` per aiutarti a vedere cosa sta succedendo. Controlla la console mentre scrivi il codice per vedere come cambia. Dichiara una variabile locale `myVar` all'interno di `myLocalScope` ed esegui i test.
|
||||
|
||||
**Nota:** La console mostrerà ancora `ReferenceError: myVar is not defined`, ma questo non causerà il fallimento dei test.
|
||||
|
||||
# --hints--
|
||||
|
||||
Il codice non dovrebbe contenere una variabile globale `myVar`.
|
||||
|
||||
```js
|
||||
function declared() {
|
||||
myVar;
|
||||
}
|
||||
assert.throws(declared, ReferenceError);
|
||||
```
|
||||
|
||||
Dovresti aggiungere una variabile locale `myVar`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/functionmyLocalScope\(\)\{.*(var|let|const)myVar[\s\S]*}/.test(
|
||||
__helpers.removeWhiteSpace(code)
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function myLocalScope() {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
console.log('inside myLocalScope', myVar);
|
||||
}
|
||||
myLocalScope();
|
||||
|
||||
// Run and check the console
|
||||
// myVar is not defined outside of myLocalScope
|
||||
console.log('outside myLocalScope', myVar);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function myLocalScope() {
|
||||
|
||||
// Only change code below this line
|
||||
var myVar;
|
||||
console.log('inside myLocalScope', myVar);
|
||||
}
|
||||
myLocalScope();
|
||||
|
||||
// Run and check the console
|
||||
// myVar is not defined outside of myLocalScope
|
||||
console.log('outside myLocalScope', myVar);
|
||||
```
|
@ -0,0 +1,109 @@
|
||||
---
|
||||
id: 5690307fddb111c6084545d7
|
||||
title: Ordine logico nelle istruzioni If/Else
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cwNvMUV'
|
||||
forumTopicId: 18228
|
||||
dashedName: logical-order-in-if-else-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
L'ordine è importante nelle istruzioni `if`, `else if`.
|
||||
|
||||
La funzione viene eseguita dall'alto verso il basso, quindi dovrai fare attenzione a quale istruzione viene prima.
|
||||
|
||||
Prendiamo queste due funzioni come esempio.
|
||||
|
||||
Ecco la prima:
|
||||
|
||||
```js
|
||||
function foo(x) {
|
||||
if (x < 1) {
|
||||
return "Less than one";
|
||||
} else if (x < 2) {
|
||||
return "Less than two";
|
||||
} else {
|
||||
return "Greater than or equal to two";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
E la secondo cambia semplicemente l'ordine delle dichiarazioni:
|
||||
|
||||
```js
|
||||
function bar(x) {
|
||||
if (x < 2) {
|
||||
return "Less than two";
|
||||
} else if (x < 1) {
|
||||
return "Less than one";
|
||||
} else {
|
||||
return "Greater than or equal to two";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Anche se queste due funzioni sembrano quasi identiche, se passiamo un numero ad entrambe otterremo output diversi.
|
||||
|
||||
```js
|
||||
foo(0)
|
||||
bar(0)
|
||||
```
|
||||
|
||||
`foo(0)` restituirà la stringa `Less than one`, e `bar(0)` restituirà la stringa `Less than two`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Cambia l'ordine della logica nella funzione in modo che restituisca le affermazioni corrette in tutti i casi.
|
||||
|
||||
# --hints--
|
||||
|
||||
`orderMyLogic(4)` dovrebbe restituire la stringa `Less than 5`
|
||||
|
||||
```js
|
||||
assert(orderMyLogic(4) === 'Less than 5');
|
||||
```
|
||||
|
||||
`orderMyLogic(6)` dovrebbe restituire la stringa `Less than 10`
|
||||
|
||||
```js
|
||||
assert(orderMyLogic(6) === 'Less than 10');
|
||||
```
|
||||
|
||||
`orderMyLogic(11)` dovrebbe restituire la stringa `Greater than or equal to 10`
|
||||
|
||||
```js
|
||||
assert(orderMyLogic(11) === 'Greater than or equal to 10');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function orderMyLogic(val) {
|
||||
if (val < 10) {
|
||||
return "Less than 10";
|
||||
} else if (val < 5) {
|
||||
return "Less than 5";
|
||||
} else {
|
||||
return "Greater than or equal to 10";
|
||||
}
|
||||
}
|
||||
|
||||
orderMyLogic(7);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function orderMyLogic(val) {
|
||||
if(val < 5) {
|
||||
return "Less than 5";
|
||||
} else if (val < 10) {
|
||||
return "Less than 10";
|
||||
} else {
|
||||
return "Greater than or equal to 10";
|
||||
}
|
||||
}
|
||||
```
|
@ -0,0 +1,90 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392cc
|
||||
title: Manipolare gli array con pop()
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRbVZAB'
|
||||
forumTopicId: 18236
|
||||
dashedName: manipulate-arrays-with-pop
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Un altro modo per cambiare i dati in un array è con la funzione `.pop()`.
|
||||
|
||||
`.pop()` è usato per estrarre un valore dalla fine di un array. Possiamo memorizzare questo valore assegnandolo ad una variabile. In altre parole, `.pop()` rimuove l'ultimo elemento da un array e restituisce quell'elemento.
|
||||
|
||||
Qualsiasi tipo di elemento può essere estratto da un array - numeri, stringhe, anche array annidati.
|
||||
|
||||
```js
|
||||
var threeArr = [1, 4, 6];
|
||||
var oneDown = threeArr.pop();
|
||||
console.log(oneDown);
|
||||
console.log(threeArr);
|
||||
```
|
||||
|
||||
Il primo `console.log` mostrerà il valore `6`e il secondo mostrerà il valore `[1, 4]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Utilizza la funzione `.pop()` per rimuovere l'ultimo elemento da `myArray`, assegnando il valore estratto a `removedFromMyArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` dovrebbe contenere solo `[["John", 23]]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (d) {
|
||||
if (d[0][0] == 'John' && d[0][1] === 23 && d[1] == undefined) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myArray)
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti usare `pop()` su `myArray`.
|
||||
|
||||
```js
|
||||
assert(/removedFromMyArray\s*=\s*myArray\s*.\s*pop\s*(\s*)/.test(code));
|
||||
```
|
||||
|
||||
`removedFromMyArray` dovrebbe contenere solo `["cat", 2]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (d) {
|
||||
if (d[0] == 'cat' && d[1] === 2 && d[2] == undefined) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(removedFromMyArray)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
var removedFromMyArray = myArray.pop();
|
||||
```
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392cb
|
||||
title: Manipolare gli array con push()
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cnqmVtJ'
|
||||
forumTopicId: 18237
|
||||
dashedName: manipulate-arrays-with-push
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Un modo semplice per aggiungere dei dati alla fine di un array è tramite la funzione `push()`.
|
||||
|
||||
`.push()` prende uno o più <dfn>parametri</dfn> e li "spinge" alla fine dell'array.
|
||||
|
||||
Esempi:
|
||||
|
||||
```js
|
||||
var arr1 = [1,2,3];
|
||||
arr1.push(4);
|
||||
|
||||
var arr2 = ["Stimpson", "J", "cat"];
|
||||
arr2.push(["happy", "joy"]);
|
||||
```
|
||||
|
||||
`arr1` ora ha il valore `[1, 2, 3, 4]` e `arr2` ha il valore `["Stimpson", "J", "cat", ["happy", "joy"]]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Inserisci `["dog", 3]` in fondo alla variabile `myArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` ora dovrebbe essere uguale a `[["John", 23], ["cat", 2], ["dog", 3]]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (d) {
|
||||
if (
|
||||
d[2] != undefined &&
|
||||
d[0][0] == 'John' &&
|
||||
d[0][1] === 23 &&
|
||||
d[2][0] == 'dog' &&
|
||||
d[2][1] === 3 &&
|
||||
d[2].length == 2
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myArray)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'myArray = ' + JSON.stringify(z);})(myArray);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
myArray.push(["dog",3]);
|
||||
```
|
@ -0,0 +1,88 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392cd
|
||||
title: Manipolare gli array con shift()
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRbVETW'
|
||||
forumTopicId: 18238
|
||||
dashedName: manipulate-arrays-with-shift
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`pop()` rimuove sempre l'ultimo elemento di un array. E se volessi rimuovere il primo?
|
||||
|
||||
È qui che entra in gioco `.shift()`. Funziona proprio come `.pop()`, solo che rimuove il primo elemento invece dell'ultimo.
|
||||
|
||||
Esempio:
|
||||
|
||||
```js
|
||||
var ourArray = ["Stimpson", "J", ["cat"]];
|
||||
var removedFromOurArray = ourArray.shift();
|
||||
```
|
||||
|
||||
`removedFromOurArray` dovrebbe avere un valore stringa `Stimpson`e `ourArray` dovrebbe valere `["J", ["cat"]]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Utilizza la funzione `.shift()` per rimuovere il primo elemento da `myArray`, assegnando il valore "spostato" a `removedFromMyArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` dovrebbe ora essere uguale a `[["dog", 3]]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (d) {
|
||||
if (d[0][0] == 'dog' && d[0][1] === 3 && d[1] == undefined) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myArray)
|
||||
);
|
||||
```
|
||||
|
||||
`removedFromMyArray` dovrebbe contenere `["John", 23]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (d) {
|
||||
if (
|
||||
d[0] == 'John' &&
|
||||
d[1] === 23 &&
|
||||
typeof removedFromMyArray === 'object'
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(removedFromMyArray)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray = myArray.shift();
|
||||
```
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392ce
|
||||
title: Manipolare gli array con unshift()
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ckNDESv'
|
||||
forumTopicId: 18239
|
||||
dashedName: manipulate-arrays-with-unshift
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Non puoi solo fare uno `shift` di elementi dall'inizio di un array: puoi anche fare un `unshift`, cioè aggiungere elementi all'inizio dell'array.
|
||||
|
||||
`.unshift()` funziona esattamente come `.push()`, ma invece di aggiungere l'elemento alla fine dell'array, `unshift()` lo aggiunge all'inizio.
|
||||
|
||||
Esempio:
|
||||
|
||||
```js
|
||||
var ourArray = ["Stimpson", "J", "cat"];
|
||||
ourArray.shift();
|
||||
ourArray.unshift("Happy");
|
||||
```
|
||||
|
||||
Dopo lo `shift`, `ourArray` avrà il valore `["J", "cat"]`. Dopo l'`unshift`, `ourArray` avrà il valore `["Happy", "J", "cat"]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Aggiungi `["Paul",35]` all'inizio della variabile `myArray` usando `unshift()`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` ora dovrebbe valere `[["Paul", 35], ["dog", 3]]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (d) {
|
||||
if (
|
||||
typeof d[0] === 'object' &&
|
||||
d[0][0] == 'Paul' &&
|
||||
d[0][1] === 35 &&
|
||||
d[1][0] != undefined &&
|
||||
d[1][0] == 'dog' &&
|
||||
d[1][1] != undefined &&
|
||||
d[1][1] == 3
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myArray)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y, z){return 'myArray = ' + JSON.stringify(y);})(myArray);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
myArray.shift();
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
myArray.shift();
|
||||
myArray.unshift(["Paul", 35]);
|
||||
```
|
@ -0,0 +1,179 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cb
|
||||
title: Manipolare oggetti complessi
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9yNMfR'
|
||||
forumTopicId: 18208
|
||||
dashedName: manipulating-complex-objects
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A volte potresti voler memorizzare i dati in una <dfn>struttura di dati</dfn> flessibile. Un oggetto JavaScript è un modo per gestire dati flessibili. Gli oggetti consentono combinazioni arbitrarie di <dfn>stringhe</dfn>, <dfn>numeri</dfn>, <dfn>booleani</dfn>, <dfn>array</dfn>, <dfn>funzioni</dfn> e <dfn>oggetti</dfn>.
|
||||
|
||||
Ecco un esempio di struttura di dati complessa:
|
||||
|
||||
```js
|
||||
var ourMusic = [
|
||||
{
|
||||
"artist": "Daft Punk",
|
||||
"title": "Homework",
|
||||
"release_year": 1997,
|
||||
"formats": [
|
||||
"CD",
|
||||
"Cassette",
|
||||
"LP"
|
||||
],
|
||||
"gold": true
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
Questo è un array che contiene un oggetto al suo interno. L'oggetto ha vari pezzi di <dfn>metadati</dfn> riguardanti un album. Ha anche un array annidato `formats`. Se volessi aggiungere più record di tipo album, potresti farlo aggiungendo dei record all'array di livello superiore. Gli oggetti contengono i dati nelle proprietà, che hanno un formato chiave-valore (key-value). Nell'esempio sopra, `"artist": "Daft Punk"` è una proprietà che ha una chiave `artist` e un valore `Daft Punk`. [JavaScript Object Notation](http://www.json.org/) o `JSON` è un formato di scambio di dati, utilizzato per memorizzare dati.
|
||||
|
||||
```json
|
||||
{
|
||||
"artist": "Daft Punk",
|
||||
"title": "Homework",
|
||||
"release_year": 1997,
|
||||
"formats": [
|
||||
"CD",
|
||||
"Cassette",
|
||||
"LP"
|
||||
],
|
||||
"gold": true
|
||||
}
|
||||
```
|
||||
|
||||
**Nota:** Dovrai inserire una virgola dopo ogni oggetto nell'array, a meno che non sia l'ultimo.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Aggiungi un nuovo album all'array `myMusic`. Aggiungi le stringhe `artist` e `title`, il numero `release_year` e un array di stringhe `formats`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myMusic` dovrebbe essere un array
|
||||
|
||||
```js
|
||||
assert(Array.isArray(myMusic));
|
||||
```
|
||||
|
||||
`myMusic` dovrebbe avere almeno due elementi
|
||||
|
||||
```js
|
||||
assert(myMusic.length > 1);
|
||||
```
|
||||
|
||||
Gli elementi dell'array `myMusic` dovrebbero essere oggetti
|
||||
|
||||
```js
|
||||
myMusic.forEach(object => {assert.typeOf(object, 'object')})
|
||||
```
|
||||
|
||||
Il tuo oggetto in `myMusic` dovrebbe avere almeno 4 proprietà
|
||||
|
||||
```js
|
||||
myMusic.forEach(object => {assert(Object.keys(object).length > 3); });
|
||||
```
|
||||
|
||||
Il tuo oggetto in `myMusic` dovrebbe contenere la proprietà `artist`, di tipo string
|
||||
|
||||
```js
|
||||
myMusic.forEach(object => {
|
||||
assert.containsAllKeys(object, ['artist']);
|
||||
assert.typeOf(object.artist, 'string')
|
||||
})
|
||||
```
|
||||
|
||||
Il tuo oggetto in `myMusic` dovrebbe contenere la proprietà `title`, di tipo string
|
||||
|
||||
```js
|
||||
myMusic.forEach(object => {
|
||||
assert.containsAllKeys(object, ['title']);
|
||||
assert.typeOf(object.title, 'string')
|
||||
})
|
||||
```
|
||||
|
||||
Il tuo oggetto in `myMusic` dovrebbe contenere la proprietà `release_year`, di tipo number
|
||||
|
||||
```js
|
||||
myMusic.forEach(object => {
|
||||
assert.containsAllKeys(object, ['release_year']);
|
||||
assert.typeOf(object.release_year, 'number')
|
||||
})
|
||||
```
|
||||
|
||||
Il tuo oggetto in `myMusic` dovrebbe contenere una proprietà `formats`, di tipo array
|
||||
|
||||
```js
|
||||
myMusic.forEach(object => {
|
||||
assert.containsAllKeys(object, ['formats']);
|
||||
assert.typeOf(object.formats, 'array')
|
||||
})
|
||||
```
|
||||
|
||||
`formats` dovrebbe essere un array di stringhe con almeno due elementi
|
||||
|
||||
```js
|
||||
myMusic.forEach(object => {
|
||||
object.formats.forEach(format => {
|
||||
assert.typeOf(format, 'string')
|
||||
});
|
||||
assert.isAtLeast(object.formats.length, 2)
|
||||
})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(x){ if (Array.isArray(x)) { return JSON.stringify(x); } return "myMusic is not an array"})(myMusic);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myMusic = [
|
||||
{
|
||||
"artist": "Billy Joel",
|
||||
"title": "Piano Man",
|
||||
"release_year": 1973,
|
||||
"formats": [
|
||||
"CD",
|
||||
"8T",
|
||||
"LP"
|
||||
],
|
||||
"gold": true
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myMusic = [
|
||||
{
|
||||
"artist": "Billy Joel",
|
||||
"title": "Piano Man",
|
||||
"release_year": 1973,
|
||||
"formats": [
|
||||
"CS",
|
||||
"8T",
|
||||
"LP" ],
|
||||
"gold": true
|
||||
},
|
||||
{
|
||||
"artist": "ABBA",
|
||||
"title": "Ring Ring",
|
||||
"release_year": 1973,
|
||||
"formats": [
|
||||
"CS",
|
||||
"8T",
|
||||
"LP",
|
||||
"CD",
|
||||
]
|
||||
}
|
||||
];
|
||||
```
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb8bdef
|
||||
title: Modificare i dati dell'array con gli indici
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/czQM4A8'
|
||||
forumTopicId: 18241
|
||||
dashedName: modify-array-data-with-indexes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A differenza delle stringhe, gli elementi degli array sono <dfn>mutabili</dfn> e possono essere cambiati liberamente.
|
||||
|
||||
**Esempio**
|
||||
|
||||
```js
|
||||
var ourArray = [50,40,30];
|
||||
ourArray[0] = 15;
|
||||
```
|
||||
|
||||
`ourArray` ha ora il valore `[15, 40, 30]`.
|
||||
|
||||
**Note:** Non ci dovrebbero essere spazi tra il nome dell'array e le parentesi quadre, come in `array [0]`. Anche se JavaScript è in grado di elaborarlo correttamente, questo potrebbe confondere altri programmatori che leggessero il tuo codice.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modificare i dati memorizzati all'indice `0` di `myArray` a un valore di `45`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` dovrebbe ora essere `[45,64,99]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (
|
||||
typeof myArray != 'undefined' &&
|
||||
myArray[0] == 45 &&
|
||||
myArray[1] == 64 &&
|
||||
myArray[2] == 99
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti usare l'indice corretto per modificare il valore in `myArray`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (code.match(/myArray\[0\]\s*=\s*/g)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [18,64,99];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [18,64,99];
|
||||
myArray[0] = 45;
|
||||
```
|
@ -0,0 +1,149 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244df
|
||||
title: Opzioni identiche multiple nelle dichiarazioni Switch
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cdBKWCV'
|
||||
forumTopicId: 18242
|
||||
dashedName: multiple-identical-options-in-switch-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Se l'istruzione `break` viene omessa da un'istruzione `switch` e in particolare da un suo `case`, le istruzione `case` successive sono eseguite fino a quando non si incontra un `break`. Se hai diversi input con lo stesso output, potrai rappresentarli in un'istruzione `switch` come la seguente:
|
||||
|
||||
```js
|
||||
var result = "";
|
||||
switch(val) {
|
||||
case 1:
|
||||
case 2:
|
||||
case 3:
|
||||
result = "1, 2, or 3";
|
||||
break;
|
||||
case 4:
|
||||
result = "4 alone";
|
||||
}
|
||||
```
|
||||
|
||||
I casi per 1, 2 e 3 produrranno tutti lo stesso risultato.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Scrivi una dichiarazione di switch per impostare `answer` per i seguenti intervalli:
|
||||
`1-3` - `Low`
|
||||
`4-6` - `Mid`
|
||||
`7-9` - `High`
|
||||
|
||||
**Note:** Dovrai avere un `case` per ogni numero nell'intervallo.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sequentialSizes(1)` dovrebbe restituire la stringa `Low`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(1) === 'Low');
|
||||
```
|
||||
|
||||
`sequentialSizes(2)` dovrebbe restituire la stringa `Low`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(2) === 'Low');
|
||||
```
|
||||
|
||||
`sequentialSizes(3)` dovrebbe restituire la stringa `Low`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(3) === 'Low');
|
||||
```
|
||||
|
||||
`sequentialSizes(4)` dovrebbe restituire la stringa `Mid`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(4) === 'Mid');
|
||||
```
|
||||
|
||||
`sequentialSizes(5)` dovrebbe restituire la stringa `Mid`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(5) === 'Mid');
|
||||
```
|
||||
|
||||
`sequentialSizes(6)` dovrebbe restituire la stringa `Mid`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(6) === 'Mid');
|
||||
```
|
||||
|
||||
`sequentialSizes(7)` dovrebbe restituire la stringa `High`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(7) === 'High');
|
||||
```
|
||||
|
||||
`sequentialSizes(8)` dovrebbe restituire la stringa `High`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(8) === 'High');
|
||||
```
|
||||
|
||||
`sequentialSizes(9)` dovrebbe restituire la stringa `High`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(9) === 'High');
|
||||
```
|
||||
|
||||
Non dovresti usare alcuna dichiarazione `if` o `else`
|
||||
|
||||
```js
|
||||
assert(!/else/g.test(code) || !/if/g.test(code));
|
||||
```
|
||||
|
||||
Dovresti avere nove dichiarazioni `case`
|
||||
|
||||
```js
|
||||
assert(code.match(/case/g).length === 9);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sequentialSizes(val) {
|
||||
var answer = "";
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
return answer;
|
||||
}
|
||||
|
||||
sequentialSizes(1);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function sequentialSizes(val) {
|
||||
var answer = "";
|
||||
|
||||
switch(val) {
|
||||
case 1:
|
||||
case 2:
|
||||
case 3:
|
||||
answer = "Low";
|
||||
break;
|
||||
case 4:
|
||||
case 5:
|
||||
case 6:
|
||||
answer = "Mid";
|
||||
break;
|
||||
case 7:
|
||||
case 8:
|
||||
case 9:
|
||||
answer = "High";
|
||||
}
|
||||
|
||||
return answer;
|
||||
}
|
||||
```
|
@ -0,0 +1,52 @@
|
||||
---
|
||||
id: bd7993c9c69feddfaeb7bdef
|
||||
title: Moltiplicare due decimali con JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ce2GeHq'
|
||||
forumTopicId: 301173
|
||||
dashedName: multiply-two-decimals-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, è anche possibile eseguire calcoli con numeri decimali, proprio come con i numeri interi.
|
||||
|
||||
Moltiplichiamo due decimali insieme per ottenere il loro prodotto.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Cambia lo `0.0` in modo che il prodotto sia uguale a `5.0`.
|
||||
|
||||
# --hints--
|
||||
|
||||
La variabile `product` dovrebbe essere uguale a `5.0`.
|
||||
|
||||
```js
|
||||
assert(product === 5.0);
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `*`
|
||||
|
||||
```js
|
||||
assert(/\*/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y){return 'product = '+y;})(product);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var product = 2.0 * 0.0;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var product = 2.0 * 2.5;
|
||||
```
|
@ -0,0 +1,60 @@
|
||||
---
|
||||
id: cf1231c1c11feddfaeb5bdef
|
||||
title: Moltiplicare due numeri con JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cP3y3Aq'
|
||||
forumTopicId: 18243
|
||||
dashedName: multiply-two-numbers-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Possiamo anche moltiplicare un numero per un altro.
|
||||
|
||||
JavaScript utilizza il simbolo `*` per la moltiplicazione di due numeri.
|
||||
|
||||
**Esempio**
|
||||
|
||||
```js
|
||||
myVar = 13 * 13;
|
||||
```
|
||||
|
||||
`myVar` dovrebbe avere il valore `169`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Cambia lo `0` in modo che il prodotto sia uguale a `80`.
|
||||
|
||||
# --hints--
|
||||
|
||||
La variabile `product` dovrebbe essere uguale a 80.
|
||||
|
||||
```js
|
||||
assert(product === 80);
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `*`.
|
||||
|
||||
```js
|
||||
assert(/\*/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'product = '+z;})(product);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var product = 8 * 0;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var product = 8 * 10;
|
||||
```
|
@ -0,0 +1,51 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb7bdef
|
||||
title: Nidificare un array in un altro array
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/crZQZf8'
|
||||
forumTopicId: 18247
|
||||
dashedName: nest-one-array-within-another-array
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
È anche possibile nidificare array all'interno di altri array, come nell'esempio:
|
||||
|
||||
```js
|
||||
[["Bulls", 23], ["White Sox", 45]]
|
||||
```
|
||||
|
||||
Questo viene anche chiamato un <dfn>array multidimensionale</dfn>.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Crea un array annidato chiamato `myArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` dovrebbe avere almeno un array annidato all'interno di un altro array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(myArray) && myArray.some(Array.isArray));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
var myArray = [];
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [[1,2,3]];
|
||||
```
|
@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244e1
|
||||
title: Annidare i cicli For
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRn6GHM'
|
||||
forumTopicId: 18248
|
||||
dashedName: nesting-for-loops
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Se disponi di un array multidimensionale, è possibile utilizzare la stessa logica del punto precedente per iterare sia attraverso l'array che attraverso i suoi sottoarray. Ecco un esempio:
|
||||
|
||||
```js
|
||||
var arr = [
|
||||
[1,2], [3,4], [5,6]
|
||||
];
|
||||
for (var i=0; i < arr.length; i++) {
|
||||
for (var j=0; j < arr[i].length; j++) {
|
||||
console.log(arr[i][j]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Questo invia alla console ogni elemento presente in `arr`, uno alla volta. Nota che nel ciclo interno leggiamo la `.length` di `arr[i]`, dal momento che `arr[i]` è esso stesso un array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modifica la funzione `multiplyAll` in modo che restituisca il prodotto di tutti i numeri nei sotto-array di `arr`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`multiplyAll([[1],[2],[3]])` dovrebbe restituire `6`
|
||||
|
||||
```js
|
||||
assert(multiplyAll([[1], [2], [3]]) === 6);
|
||||
```
|
||||
|
||||
`multiplyAll([[1,2],[3,4],[5,6,7]])` dovrebbe restituire `5040`
|
||||
|
||||
```js
|
||||
assert(
|
||||
multiplyAll([
|
||||
[1, 2],
|
||||
[3, 4],
|
||||
[5, 6, 7]
|
||||
]) === 5040
|
||||
);
|
||||
```
|
||||
|
||||
`multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])` dovrebbe restituire `54`
|
||||
|
||||
```js
|
||||
assert(
|
||||
multiplyAll([
|
||||
[5, 1],
|
||||
[0.2, 4, 0.5],
|
||||
[3, 9]
|
||||
]) === 54
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function multiplyAll(arr) {
|
||||
var product = 1;
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
return product;
|
||||
}
|
||||
|
||||
multiplyAll([[1,2],[3,4],[5,6,7]]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function multiplyAll(arr) {
|
||||
var product = 1;
|
||||
for (var i = 0; i < arr.length; i++) {
|
||||
for (var j = 0; j < arr[i].length; j++) {
|
||||
product *= arr[i][j];
|
||||
}
|
||||
}
|
||||
return product;
|
||||
}
|
||||
|
||||
multiplyAll([[1,2],[3,4],[5,6,7]]);
|
||||
```
|
@ -0,0 +1,120 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244bd
|
||||
title: Passare i valori alle funzioni con gli argomenti
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cy8rahW'
|
||||
forumTopicId: 18254
|
||||
dashedName: passing-values-to-functions-with-arguments
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
I <dfn>parametri</dfn> sono variabili che agiscono come segnaposto per i valori che devono essere inseriti in una funzione quando viene chiamata. Quando una funzione viene definita, essa è tipicamente definita insieme a uno o più parametri. I valori effettivi che vengono inseriti (o <dfn>"passati"</dfn>) in una funzione quando viene chiamata sono conosciuti come <dfn>argomenti</dfn>.
|
||||
|
||||
Ecco una funzione con due parametri, `param1` e `param2`:
|
||||
|
||||
```js
|
||||
function testFun(param1, param2) {
|
||||
console.log(param1, param2);
|
||||
}
|
||||
```
|
||||
|
||||
Quindi possiamo chiamare `testFun` in questo modo: `testFun("Hello", "World");`. Abbiamo passato due argomenti stringa, `Hello` e `World`. All'interno della funzione, `param1` sarà uguale alla stringa `Hello` e `param2` sarà uguale alla stringa `World`. Nota che potresti chiamare `testFun` di nuovo con argomenti differenti e i parametri assumerebbero il valore dei nuovi argomenti.
|
||||
|
||||
# --instructions--
|
||||
|
||||
<ol><li>Crea una funzione chiamata <code>functionWithArgs</code> che accetta due argomenti e invia la loro somma alla dev console.</li><li>Chiama la funzione con due numeri come argomenti.</li></ol>
|
||||
|
||||
# --hints--
|
||||
|
||||
`functionWithArgs` dovrebbe essere una funzione.
|
||||
|
||||
```js
|
||||
assert(typeof functionWithArgs === 'function');
|
||||
```
|
||||
|
||||
`functionWithArgs(1,2)` dovrebbe produrre `3`.
|
||||
|
||||
```js
|
||||
if (typeof functionWithArgs === 'function') {
|
||||
capture();
|
||||
functionWithArgs(1, 2);
|
||||
uncapture();
|
||||
}
|
||||
assert(logOutput == 3);
|
||||
```
|
||||
|
||||
`functionWithArgs(7,9)` dovrebbe produrre `16`.
|
||||
|
||||
```js
|
||||
if (typeof functionWithArgs === 'function') {
|
||||
capture();
|
||||
functionWithArgs(7, 9);
|
||||
uncapture();
|
||||
}
|
||||
assert(logOutput == 16);
|
||||
```
|
||||
|
||||
Dovresti chiamare `functionWithArgs` con due numeri dopo averla definita.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/functionWithArgs\([-+]?\d*\.?\d*,[-+]?\d*\.?\d*\)/.test(
|
||||
code.replace(/\s/g, '')
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
var logOutput = "";
|
||||
var originalConsole = console
|
||||
function capture() {
|
||||
var nativeLog = console.log;
|
||||
console.log = function (message) {
|
||||
if(message) logOutput = JSON.stringify(message).trim();
|
||||
if(nativeLog.apply) {
|
||||
nativeLog.apply(originalConsole, arguments);
|
||||
} else {
|
||||
var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');
|
||||
nativeLog(nativeMsg);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function uncapture() {
|
||||
console.log = originalConsole.log;
|
||||
}
|
||||
|
||||
capture();
|
||||
```
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
uncapture();
|
||||
|
||||
if (typeof functionWithArgs !== "function") {
|
||||
(function() { return "functionWithArgs is not defined"; })();
|
||||
} else {
|
||||
(function() { return logOutput || "console.log never called"; })();
|
||||
}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function functionWithArgs(a, b) {
|
||||
console.log(a + b);
|
||||
}
|
||||
functionWithArgs(10, 5);
|
||||
```
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 599a789b454f2bbd91a3ff4d
|
||||
title: Confrontare diversi valori
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cm8PqCa'
|
||||
forumTopicId: 301174
|
||||
dashedName: practice-comparing-different-values
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Nelle ultime due sfide, abbiamo imparato a conoscere l'operatore di uguaglianza (`==`) e l'operatore di uguaglianza stretta (`===`). Facciamo un rapido ripasso usando ancora un po' questi operatori.
|
||||
|
||||
Se i valori confrontati non sono dello stesso tipo, l'operatore di uguaglianza eseguirà una conversione di tipo e quindi valuterà i valori. L'operatore di uguaglianza stretta invece confronterà sia il tipo di dati che il valore così com'è, senza convertire un tipo in un altro.
|
||||
|
||||
**Esempi**
|
||||
|
||||
`3 == '3'` restituisce `true` perché JavaScript esegue la conversione di tipo da string a number. `3 === '3'` restituisce false perché i tipi sono diversi e la conversione di tipo non viene eseguita.
|
||||
|
||||
**Nota:** In JavaScript, è possibile determinare il tipo di una variabile o di un valore con l'operatore `typeof`, come segue:
|
||||
|
||||
```js
|
||||
typeof 3
|
||||
typeof '3'
|
||||
```
|
||||
|
||||
`typeof 3` restituisce la stringa `number`e `typeof '3'` restituisce la stringa `string`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
La funzione `compareEquality` nell'editor confronta due valori utilizzando l'operatore di uguaglianza. Modificare la funzione in modo che restituisca la stringa `Equal` solo quando i valori sono strettamente uguali.
|
||||
|
||||
# --hints--
|
||||
|
||||
`compareEquality(10, "10")` dovrebbe restituire la stringa `Not Equal`
|
||||
|
||||
```js
|
||||
assert(compareEquality(10, '10') === 'Not Equal');
|
||||
```
|
||||
|
||||
`compareEquality("20", 20)` dovrebbe restituire la stringa `Not Equal`
|
||||
|
||||
```js
|
||||
assert(compareEquality('20', 20) === 'Not Equal');
|
||||
```
|
||||
|
||||
Dovresti usare l'operatore `===`
|
||||
|
||||
```js
|
||||
assert(code.match(/===/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function compareEquality(a, b) {
|
||||
if (a == b) { // Change this line
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
|
||||
compareEquality(10, "10");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function compareEquality(a,b) {
|
||||
if (a === b) {
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
```
|
@ -0,0 +1,151 @@
|
||||
---
|
||||
id: 5688e62ea601b2482ff8422b
|
||||
title: Ricerca di un profilo
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDqW2Cg'
|
||||
forumTopicId: 18259
|
||||
dashedName: profile-lookup
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Abbiamo un array di oggetti che rappresentano persone diverse nelle nostre liste di contatti.
|
||||
|
||||
Abbiamo scritto per te una funzione `lookUpProfile` che prende `name` e una proprietà (`prop`) come argomenti.
|
||||
|
||||
La funzione dovrebbe controllare se `name` è il `firstName` di un contatto effettivo e la proprietà specificata (`prop`) è una proprietà di quel contatto.
|
||||
|
||||
Se entrambe le condizioni sono soddisfatte, restituisce il "valore" di quella proprietà.
|
||||
|
||||
Se `name` non corrisponde a nessun contatto, restituisce la stringa `No such contact`.
|
||||
|
||||
Se `prop` non corrisponde ad alcuna proprietà valida di un contatto trovato cercando `name`, restituisce la stringa `No such property`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`lookUpProfile("Kristian", "lastName")` dovrebbe restituire la stringa `Vos`
|
||||
|
||||
```js
|
||||
assert(lookUpProfile('Kristian', 'lastName') === 'Vos');
|
||||
```
|
||||
|
||||
`lookUpProfile("Sherlock", "likes")` dovrebbe restituire `["Intriguing Cases", "Violin"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(lookUpProfile('Sherlock', 'likes'), [
|
||||
'Intriguing Cases',
|
||||
'Violin'
|
||||
]);
|
||||
```
|
||||
|
||||
`lookUpProfile("Harry", "likes")` dovrebbe restituire un array
|
||||
|
||||
```js
|
||||
assert(typeof lookUpProfile('Harry', 'likes') === 'object');
|
||||
```
|
||||
|
||||
`lookUpProfile("Bob", "number")` dovrebbe restituire la stringa `No such contact`
|
||||
|
||||
```js
|
||||
assert(lookUpProfile('Bob', 'number') === 'No such contact');
|
||||
```
|
||||
|
||||
`lookUpProfile("Bob", "potato")` dovrebbe restituire la stringa `No such contact`
|
||||
|
||||
```js
|
||||
assert(lookUpProfile('Bob', 'potato') === 'No such contact');
|
||||
```
|
||||
|
||||
`lookUpProfile("Akira", "address")` dovrebbe restituire la stringa `No such property`
|
||||
|
||||
```js
|
||||
assert(lookUpProfile('Akira', 'address') === 'No such property');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var contacts = [
|
||||
{
|
||||
"firstName": "Akira",
|
||||
"lastName": "Laine",
|
||||
"number": "0543236543",
|
||||
"likes": ["Pizza", "Coding", "Brownie Points"]
|
||||
},
|
||||
{
|
||||
"firstName": "Harry",
|
||||
"lastName": "Potter",
|
||||
"number": "0994372684",
|
||||
"likes": ["Hogwarts", "Magic", "Hagrid"]
|
||||
},
|
||||
{
|
||||
"firstName": "Sherlock",
|
||||
"lastName": "Holmes",
|
||||
"number": "0487345643",
|
||||
"likes": ["Intriguing Cases", "Violin"]
|
||||
},
|
||||
{
|
||||
"firstName": "Kristian",
|
||||
"lastName": "Vos",
|
||||
"number": "unknown",
|
||||
"likes": ["JavaScript", "Gaming", "Foxes"]
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
function lookUpProfile(name, prop){
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
lookUpProfile("Akira", "likes");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var contacts = [
|
||||
{
|
||||
"firstName": "Akira",
|
||||
"lastName": "Laine",
|
||||
"number": "0543236543",
|
||||
"likes": ["Pizza", "Coding", "Brownie Points"]
|
||||
},
|
||||
{
|
||||
"firstName": "Harry",
|
||||
"lastName": "Potter",
|
||||
"number": "0994372684",
|
||||
"likes": ["Hogwarts", "Magic", "Hagrid"]
|
||||
},
|
||||
{
|
||||
"firstName": "Sherlock",
|
||||
"lastName": "Holmes",
|
||||
"number": "0487345643",
|
||||
"likes": ["Intriguing Cases", "Violin"]
|
||||
},
|
||||
{
|
||||
"firstName": "Kristian",
|
||||
"lastName": "Vos",
|
||||
"number": "unknown",
|
||||
"likes": ["JavaScript", "Gaming", "Foxes"]
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
//Write your function in between these comments
|
||||
function lookUpProfile(name, prop){
|
||||
for(var i in contacts){
|
||||
if(contacts[i].firstName === name) {
|
||||
return contacts[i][prop] || "No such property";
|
||||
}
|
||||
}
|
||||
return "No such contact";
|
||||
}
|
||||
//Write your function in between these comments
|
||||
|
||||
lookUpProfile("Akira", "likes");
|
||||
```
|
@ -0,0 +1,81 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b4
|
||||
title: Definire le stringhe con virgolette singole
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cbQmnhM'
|
||||
forumTopicId: 18260
|
||||
dashedName: quoting-strings-with-single-quotes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
I valori <dfn>Stringa</dfn> in JavaScript possono essere scritti con virgolette singole o doppie, purché si inizi e si termini con lo stesso tipo di virgolette. A differenza di alcuni altri linguaggi di programmazione, le virgolette singole e doppie funzionano allo stesso modo in JavaScript.
|
||||
|
||||
```js
|
||||
doubleQuoteStr = "This is a string";
|
||||
singleQuoteStr = 'This is also a string';
|
||||
```
|
||||
|
||||
Il motivo per cui potresti voler usare un tipo di virgolette piuttosto dell'altro è se volessi usare entrambi in una stringa. Questo potrebbe accadere volendo salvare una conversazione in una stringa e avendo la conversazione tra virgolette. Un altro uso sarebbe salvare un tag `<a>` con vari attributi tra virgolette, tutto all'interno di una stringa.
|
||||
|
||||
```js
|
||||
conversation = 'Finn exclaims to Jake, "Algebraic!"';
|
||||
```
|
||||
|
||||
Tuttavia, questo diventa un problema se è necessario utilizzare le virgolette più esterne al suo interno. Ricorda, una stringa ha lo stesso tipo di virgolette all'inizio e alla fine. Ma se hai la stessa virgoletta da qualche parte nel mezzo, la stringa si fermerà anzitempo e lancerà un errore.
|
||||
|
||||
```js
|
||||
goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"';
|
||||
badStr = 'Finn responds, "Let's go!"';
|
||||
```
|
||||
|
||||
Qui `badStr` genererà un errore.
|
||||
|
||||
Nel <dfn>goodStr</dfn> di cui sopra, puoi usare entrambe le virgolette in modo sicuro utilizzando la barra rovesciata `\` come carattere di escape.
|
||||
|
||||
**Nota:** La barra rovesciata `\` non dovrebbe essere confusa con la barra obliqua `/`. Non fanno la stessa cosa.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Cambia la stringa fornita in una stringa con virgolette singole all'inizio e alla fine e senza caratteri di escape.
|
||||
|
||||
In questo momento, il tag `<a>` nella stringa utilizza virgolette doppie dappertutto. È necessario cambiare le virgolette esterne in virgolette singole in modo da poter rimuovere i caratteri di escape.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti rimuovere tutte le barre rovesciate (`\`).
|
||||
|
||||
```js
|
||||
assert(
|
||||
!/\\/g.test(code) &&
|
||||
myStr.match(
|
||||
'\\s*<a href\\s*=\\s*"http://www.example.com"\\s*target\\s*=\\s*"_blank">\\s*Link\\s*</a>\\s*'
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti avere due virgolette singole `'` e quattro virgolette doppie `"`.
|
||||
|
||||
```js
|
||||
assert(code.match(/"/g).length === 4 && code.match(/'/g).length === 2);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function() { return "myStr = " + myStr; })();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myStr = "<a href=\"http://www.example.com\" target=\"_blank\">Link</a>";
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = '<a href="http://www.example.com" target="_blank">Link</a>';
|
||||
```
|
@ -0,0 +1,181 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cf
|
||||
title: Collezione di dischi
|
||||
challengeType: 1
|
||||
forumTopicId: 18261
|
||||
dashedName: record-collection
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Ti viene dato un oggetto letterale che rappresenta una parte della tua collezione di album musicali. Ogni album ha un id numerico unico come chiave, e diverse altre proprietà. Non tutti gli album hanno informazioni complete.
|
||||
|
||||
Partirai con una funzione `updateRecords` che prende un oggetto letterale, `records`, contenente la collezione di album musicali, un `id`, una proprietà `prop` (come `artist` o `tracks`), e un valore `value`. Completa la funzione usando le regole sottostanti per modificare l'oggetto passato alla funzione.
|
||||
|
||||
- La tua funzione deve sempre restituire l'intero oggetto della raccolta di dischi.
|
||||
- Se `prop` non è `tracks` e `value` non è una stringa vuota, aggiorna o imposta la `prop` di quell'album a `value`.
|
||||
- Se `prop` è `tracks` ma l'album non ha una proprietà `tracks`, crea un array vuoto e aggiungi `value` ad esso.
|
||||
- Se `prop` è `tracks` e `value` non è una stringa vuota, aggiungi `value` alla fine dell'array `tracks` già esistente.
|
||||
- Se il valore `value` è una stringa vuota, elimina la proprietà `prop` dall'album.
|
||||
|
||||
**Nota:** Una copia dell'oggetto `recordCollection` viene utilizzata per i test.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dopo aver eseguito `updateRecords(recordCollection, 5439, "artist", "ABBA")`, `artist` dovrebbe essere la stringa `ABBA`
|
||||
|
||||
```js
|
||||
assert(
|
||||
updateRecords(_recordCollection, 5439, 'artist', 'ABBA')[5439]['artist'] ===
|
||||
'ABBA'
|
||||
);
|
||||
```
|
||||
|
||||
Dopo `updateRecords(recordCollection, 5439, "tracks", "Take a Chance on Me")`, `tracks` dovrebbero avere la stringa `Take a Chance on Me` come ultimo elemento.
|
||||
|
||||
```js
|
||||
assert(
|
||||
updateRecords(_recordCollection, 5439, 'tracks', 'Take a Chance on Me')[5439][
|
||||
'tracks'
|
||||
].pop() === 'Take a Chance on Me'
|
||||
);
|
||||
```
|
||||
|
||||
Dopo `updateRecords(recordCollection, 2548, "artist", "")`, `artist` non dovrebbe essere impostato
|
||||
|
||||
```js
|
||||
updateRecords(_recordCollection, 2548, 'artist', '');
|
||||
assert(!_recordCollection[2548].hasOwnProperty('artist'));
|
||||
```
|
||||
|
||||
Dopo `updateRecords(recordCollection, 1245, "tracks", "Addicted to Love")`, `tracks` dovrebbero avere la stringa `Addicted to Love` come ultimo elemento.
|
||||
|
||||
```js
|
||||
assert(
|
||||
updateRecords(_recordCollection, 1245, 'tracks', 'Addicted to Love')[1245][
|
||||
'tracks'
|
||||
].pop() === 'Addicted to Love'
|
||||
);
|
||||
```
|
||||
|
||||
Dopo `updateRecords(recordCollection, 2468, "tracks", "Free")`, `tracks` dovrebbero avere la stringa `1999` come primo elemento.
|
||||
|
||||
```js
|
||||
assert(
|
||||
updateRecords(_recordCollection, 2468, 'tracks', 'Free')[2468][
|
||||
'tracks'
|
||||
][0] === '1999'
|
||||
);
|
||||
```
|
||||
|
||||
Dopo `updateRecords(recordCollection, 2548, "tracks", "")`, `tracks` non dovrebbe essere impostato
|
||||
|
||||
```js
|
||||
updateRecords(_recordCollection, 2548, 'tracks', '');
|
||||
assert(!_recordCollection[2548].hasOwnProperty('tracks'));
|
||||
```
|
||||
|
||||
Dopo `updateRecords(recordCollection, 1245, "albumTitle", "Riptide")`, `albumTitle` dovrebbe essere la stringa `Riptide`
|
||||
|
||||
```js
|
||||
assert(
|
||||
updateRecords(_recordCollection, 1245, 'albumTitle', 'Riptide')[1245][
|
||||
'albumTitle'
|
||||
] === 'Riptide'
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
const _recordCollection = {
|
||||
2548: {
|
||||
albumTitle: 'Slippery When Wet',
|
||||
artist: 'Bon Jovi',
|
||||
tracks: ['Let It Rock', 'You Give Love a Bad Name']
|
||||
},
|
||||
2468: {
|
||||
albumTitle: '1999',
|
||||
artist: 'Prince',
|
||||
tracks: ['1999', 'Little Red Corvette']
|
||||
},
|
||||
1245: {
|
||||
artist: 'Robert Palmer',
|
||||
tracks: []
|
||||
},
|
||||
5439: {
|
||||
albumTitle: 'ABBA Gold'
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var recordCollection = {
|
||||
2548: {
|
||||
albumTitle: 'Slippery When Wet',
|
||||
artist: 'Bon Jovi',
|
||||
tracks: ['Let It Rock', 'You Give Love a Bad Name']
|
||||
},
|
||||
2468: {
|
||||
albumTitle: '1999',
|
||||
artist: 'Prince',
|
||||
tracks: ['1999', 'Little Red Corvette']
|
||||
},
|
||||
1245: {
|
||||
artist: 'Robert Palmer',
|
||||
tracks: []
|
||||
},
|
||||
5439: {
|
||||
albumTitle: 'ABBA Gold'
|
||||
}
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
function updateRecords(records, id, prop, value) {
|
||||
return records;
|
||||
}
|
||||
|
||||
updateRecords(recordCollection, 5439, 'artist', 'ABBA');
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var recordCollection = {
|
||||
2548: {
|
||||
albumTitle: 'Slippery When Wet',
|
||||
artist: 'Bon Jovi',
|
||||
tracks: ['Let It Rock', 'You Give Love a Bad Name']
|
||||
},
|
||||
2468: {
|
||||
albumTitle: '1999',
|
||||
artist: 'Prince',
|
||||
tracks: ['1999', 'Little Red Corvette']
|
||||
},
|
||||
1245: {
|
||||
artist: 'Robert Palmer',
|
||||
tracks: []
|
||||
},
|
||||
5439: {
|
||||
albumTitle: 'ABBA Gold'
|
||||
}
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
function updateRecords(records, id, prop, value) {
|
||||
if (value === '') delete records[id][prop];
|
||||
else if (prop === 'tracks') {
|
||||
records[id][prop] = records[id][prop] || [];
|
||||
records[id][prop].push(value);
|
||||
} else {
|
||||
records[id][prop] = value;
|
||||
}
|
||||
|
||||
return records;
|
||||
}
|
||||
```
|
@ -0,0 +1,105 @@
|
||||
---
|
||||
id: 5cfa3679138e7d9595b9d9d4
|
||||
title: Sostituire i cicli usando la ricorsione
|
||||
challengeType: 1
|
||||
videoUrl: >-
|
||||
https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/
|
||||
forumTopicId: 301175
|
||||
dashedName: replace-loops-using-recursion
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
La ricorsione è il concetto che una funzione può essere espressa in termini di se stessa. Per aiutarti a comprenderlo, inizia pensando al seguente compito: moltiplica i primi `n` elementi di un array per creare il prodotto di questi elementi. Utilizzando un ciclo `for`, potresti fare così:
|
||||
|
||||
```js
|
||||
function multiply(arr, n) {
|
||||
var product = 1;
|
||||
for (var i = 0; i < n; i++) {
|
||||
product *= arr[i];
|
||||
}
|
||||
return product;
|
||||
}
|
||||
```
|
||||
|
||||
Tuttavia, nota che `multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]`. Questo significa che puoi riscrivere `multiply` in termini di se stessa e non aver mai bisogno di utilizzare un ciclo.
|
||||
|
||||
```js
|
||||
function multiply(arr, n) {
|
||||
if (n <= 0) {
|
||||
return 1;
|
||||
} else {
|
||||
return multiply(arr, n - 1) * arr[n - 1];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
La versione ricorsiva di `multiply` si interrompe in questo modo. Nel <dfn>caso base</dfn>, dove `n <= 0`, restituisce 1. Per valori più grandi di `n`, essa chiama sé stessa, ma con `n - 1`. Quella chiamata di funzione è valutata allo stesso modo, chiamando `multiply` di nuovo fino a `n <= 0`. A questo punto, tutte le funzioni possono restituire il loro valore e l'originale `multiply` restituisce la risposta.
|
||||
|
||||
**Nota:** Le funzioni ricorsive devono avere un caso base quando ritornano senza richiamare di nuovo la funzione (in questo esempio, quando `n <= 0`), altrimenti non potranno mai finire di eseguire.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Scrivi una funzione ricorsiva, `sum(arr, n)`, che restituisce la somma dei primi elementi `n` di un array `arr`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sum([1], 0)` dovrebbe essere uguale a 0.
|
||||
|
||||
```js
|
||||
assert.equal(sum([1], 0), 0);
|
||||
```
|
||||
|
||||
`sum([2, 3, 4], 1)` dovrebbe essere uguale 2.
|
||||
|
||||
```js
|
||||
assert.equal(sum([2, 3, 4], 1), 2);
|
||||
```
|
||||
|
||||
`sum([2, 3, 4, 5], 3)` dovrebbe essere uguale 9.
|
||||
|
||||
```js
|
||||
assert.equal(sum([2, 3, 4, 5], 3), 9);
|
||||
```
|
||||
|
||||
Il tuo codice non deve fare affidamento su alcun tipo di ciclo (`for` o `while` o funzioni di ordine superiore come `forEach`, `map`, `filter` o `reduce`.).
|
||||
|
||||
```js
|
||||
assert(
|
||||
!code.match(/for|while|forEach|map|filter|reduce/g)
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti usare la ricorsione per risolvere questo problema.
|
||||
|
||||
```js
|
||||
assert(
|
||||
sum.toString().match(/sum\(.*\)/g).length > 1
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sum(arr, n) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function sum(arr, n) {
|
||||
// Only change code below this line
|
||||
if(n <= 0) {
|
||||
return 0;
|
||||
} else {
|
||||
return sum(arr, n - 1) + arr[n - 1];
|
||||
}
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
@ -0,0 +1,157 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244e0
|
||||
title: Sostituire le catene di If Else con Switch
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c3JE8fy'
|
||||
forumTopicId: 18266
|
||||
dashedName: replacing-if-else-chains-with-switch
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Se si dispone di molte opzioni tra cui scegliere, un'istruzione `switch` può essere più facile da scrivere rispetto a molte istruzioni `if`/`else if` concatenate. Il seguente:
|
||||
|
||||
```js
|
||||
if (val === 1) {
|
||||
answer = "a";
|
||||
} else if (val === 2) {
|
||||
answer = "b";
|
||||
} else {
|
||||
answer = "c";
|
||||
}
|
||||
```
|
||||
|
||||
può essere sostituito con:
|
||||
|
||||
```js
|
||||
switch(val) {
|
||||
case 1:
|
||||
answer = "a";
|
||||
break;
|
||||
case 2:
|
||||
answer = "b";
|
||||
break;
|
||||
default:
|
||||
answer = "c";
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Cambiare le istruzioni `if`/`else if` concatenate con un'istruzione `switch`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Non dovresti usare nessuna istruzione `else` nell'editor
|
||||
|
||||
```js
|
||||
assert(!/else/g.test(code));
|
||||
```
|
||||
|
||||
Non dovresti usare nessuna istruzione `if` nell'editor
|
||||
|
||||
```js
|
||||
assert(!/if/g.test(code));
|
||||
```
|
||||
|
||||
Dovresti avere almeno quattro istruzioni `break`
|
||||
|
||||
```js
|
||||
assert(code.match(/break/g).length >= 4);
|
||||
```
|
||||
|
||||
`chainToSwitch("bob")` dovrebbe essere la stringa `Marley`
|
||||
|
||||
```js
|
||||
assert(chainToSwitch('bob') === 'Marley');
|
||||
```
|
||||
|
||||
`chainToSwitch(42)` dovrebbe essere la stringa `The Answer`
|
||||
|
||||
```js
|
||||
assert(chainToSwitch(42) === 'The Answer');
|
||||
```
|
||||
|
||||
`chainToSwitch(1)` dovrebbe essere la stringa `There is no #1`
|
||||
|
||||
```js
|
||||
assert(chainToSwitch(1) === 'There is no #1');
|
||||
```
|
||||
|
||||
`chainToSwitch(99)` dovrebbe essere la stringa `Missed me by this much!`
|
||||
|
||||
```js
|
||||
assert(chainToSwitch(99) === 'Missed me by this much!');
|
||||
```
|
||||
|
||||
`chainToSwitch(7)` dovrebbe essere la stringa `Ate Nine`
|
||||
|
||||
```js
|
||||
assert(chainToSwitch(7) === 'Ate Nine');
|
||||
```
|
||||
|
||||
`chainToSwitch("John")` dovrebbe essere `""` (stringa vuota)
|
||||
|
||||
```js
|
||||
assert(chainToSwitch('John') === '');
|
||||
```
|
||||
|
||||
`chainToSwitch(156)` dovrebbe essere `""` (stringa vuota)
|
||||
|
||||
```js
|
||||
assert(chainToSwitch(156) === '');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function chainToSwitch(val) {
|
||||
var answer = "";
|
||||
// Only change code below this line
|
||||
|
||||
if (val === "bob") {
|
||||
answer = "Marley";
|
||||
} else if (val === 42) {
|
||||
answer = "The Answer";
|
||||
} else if (val === 1) {
|
||||
answer = "There is no #1";
|
||||
} else if (val === 99) {
|
||||
answer = "Missed me by this much!";
|
||||
} else if (val === 7) {
|
||||
answer = "Ate Nine";
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
return answer;
|
||||
}
|
||||
|
||||
chainToSwitch(7);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function chainToSwitch(val) {
|
||||
var answer = "";
|
||||
|
||||
switch(val) {
|
||||
case "bob":
|
||||
answer = "Marley";
|
||||
break;
|
||||
case 42:
|
||||
answer = "The Answer";
|
||||
break;
|
||||
case 1:
|
||||
answer = "There is no #1";
|
||||
break;
|
||||
case 99:
|
||||
answer = "Missed me by this much!";
|
||||
break;
|
||||
case 7:
|
||||
answer = "Ate Nine";
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
```
|
@ -0,0 +1,72 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c2
|
||||
title: Restituire un valore da una funzione con Return
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cy87wue'
|
||||
forumTopicId: 18271
|
||||
dashedName: return-a-value-from-a-function-with-return
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Possiamo passare dei valori a una funzione con gli <dfn>argomenti</dfn>. È possibile utilizzare un'istruzione `return` per fare in modo che una funzione restituisca un valore.
|
||||
|
||||
**Esempio**
|
||||
|
||||
```js
|
||||
function plusThree(num) {
|
||||
return num + 3;
|
||||
}
|
||||
var answer = plusThree(5);
|
||||
```
|
||||
|
||||
`answer` ha il valore `8`.
|
||||
|
||||
`plusThree` prende un <dfn>argomento</dfn> per `num` e restituisce un valore pari a `num + 3`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Crea una funzione `timesFive` che accetta un argomento, lo moltiplica per `5`e restituisce il nuovo valore.
|
||||
|
||||
# --hints--
|
||||
|
||||
`timesFive` dovrebbe essere una funzione
|
||||
|
||||
```js
|
||||
assert(typeof timesFive === 'function');
|
||||
```
|
||||
|
||||
`timesFive(5)` dovrebbe restituire `25`
|
||||
|
||||
```js
|
||||
assert(timesFive(5) === 25);
|
||||
```
|
||||
|
||||
`timesFive(2)` dovrebbe restituire `10`
|
||||
|
||||
```js
|
||||
assert(timesFive(2) === 10);
|
||||
```
|
||||
|
||||
`timesFive(0)` dovrebbe restituire `0`
|
||||
|
||||
```js
|
||||
assert(timesFive(0) === 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function timesFive(num) {
|
||||
return num * 5;
|
||||
}
|
||||
timesFive(10);
|
||||
```
|
@ -0,0 +1,106 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c4
|
||||
title: Pattern di ritorno precoce per le funzioni
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cQe39Sq'
|
||||
forumTopicId: 18272
|
||||
dashedName: return-early-pattern-for-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Quando viene raggiunta un'istruzione `return`, l'esecuzione della funzione corrente si interrompe e il controllo ritorna alla posizione in cui è stata chiamata la funzione.
|
||||
|
||||
**Esempio**
|
||||
|
||||
```js
|
||||
function myFun() {
|
||||
console.log("Hello");
|
||||
return "World";
|
||||
console.log("byebye")
|
||||
}
|
||||
myFun();
|
||||
```
|
||||
|
||||
Quanto sopra mostrerà la stringa `Hello` nella console, e restituirà la stringa `World`. La stringa `byebye` non verrà mai visualizzata nella console, perché la funzione esce al raggiungimento dell'istruzione `return`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modifica la funzione `abTest` in modo che se `a` o `b` sono inferiori a `0` la funzione esce immediatamente con un valore di `undefined`.
|
||||
|
||||
**Suggerimento**
|
||||
Ricorda che [`undefined` è una parola chiave](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables), non una stringa.
|
||||
|
||||
# --hints--
|
||||
|
||||
`abTest(2,2)` dovrebbe restituire un numero
|
||||
|
||||
```js
|
||||
assert(typeof abTest(2, 2) === 'number');
|
||||
```
|
||||
|
||||
`abTest(2,2)` dovrebbe restituire `8`
|
||||
|
||||
```js
|
||||
assert(abTest(2, 2) === 8);
|
||||
```
|
||||
|
||||
`abTest(-2,2)` dovrebbe restituire `undefined`
|
||||
|
||||
```js
|
||||
assert(abTest(-2, 2) === undefined);
|
||||
```
|
||||
|
||||
`abTest(2,-2)` dovrebbe restituire `undefined`
|
||||
|
||||
```js
|
||||
assert(abTest(2, -2) === undefined);
|
||||
```
|
||||
|
||||
`abTest(2,8)` dovrebbe restituire `18`
|
||||
|
||||
```js
|
||||
assert(abTest(2, 8) === 18);
|
||||
```
|
||||
|
||||
`abTest(3,3)` dovrebbe restituire `12`
|
||||
|
||||
```js
|
||||
assert(abTest(3, 3) === 12);
|
||||
```
|
||||
|
||||
`abTest(0,0)` dovrebbe restituire `0`
|
||||
|
||||
```js
|
||||
assert(abTest(0, 0) === 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function abTest(a, b) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
|
||||
}
|
||||
|
||||
abTest(2,2);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function abTest(a, b) {
|
||||
if(a < 0 || b < 0) {
|
||||
return undefined;
|
||||
}
|
||||
return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
|
||||
}
|
||||
```
|
@ -0,0 +1,82 @@
|
||||
---
|
||||
id: 5679ceb97cbaa8c51670a16b
|
||||
title: Restituire valori booleani dalle funzioni
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cp62qAQ'
|
||||
forumTopicId: 18273
|
||||
dashedName: returning-boolean-values-from-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
È possibile ricordare da [Confrontare con l'operatore di uguaglianza](/learn/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator) che tutti gli operatori di confronto restituiscono un valore booleano `true` o `false`.
|
||||
|
||||
A volte le persone usano un'istruzione `if/else` per fare un confronto, in questo modo:
|
||||
|
||||
```js
|
||||
function isEqual(a,b) {
|
||||
if (a === b) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Ma c'è un modo migliore per farlo. Dal momento che `===` restituisce `true` o `false`, possiamo restituire il risultato del confronto:
|
||||
|
||||
```js
|
||||
function isEqual(a,b) {
|
||||
return a === b;
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Correggi la funzione `isLess` per rimuovere le istruzioni `if/else`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isLess(10,15)` dovrebbe restituire `true`
|
||||
|
||||
```js
|
||||
assert(isLess(10, 15) === true);
|
||||
```
|
||||
|
||||
`isLess(15,10)` dovrebbe restituire `false`
|
||||
|
||||
```js
|
||||
assert(isLess(15, 10) === false);
|
||||
```
|
||||
|
||||
Non dovresti usare alcuna dichiarazione `if` o `else`
|
||||
|
||||
```js
|
||||
assert(!/if|else/g.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isLess(a, b) {
|
||||
// Only change code below this line
|
||||
if (a < b) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
isLess(10, 15);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isLess(a, b) {
|
||||
return a < b;
|
||||
}
|
||||
```
|
@ -0,0 +1,114 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244dd
|
||||
title: Selezionare tra molte opzioni con le istruzioni Switch
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c4mv4fm'
|
||||
forumTopicId: 18277
|
||||
dashedName: selecting-from-many-options-with-switch-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Se hai molte opzioni tra cui scegliere, usa un'istruzione <dfn>switch</dfn>. Un'istruzione `switch` verifica un valore e può avere molte istruzioni <dfn>case</dfn> che definiscono vari valori possibili. Le istruzioni vengono eseguite dal primo valore `case` che combacia e fino a quando non si incontra un `break`.
|
||||
|
||||
Ecco un esempio di un'istruzione `switch`:
|
||||
|
||||
```js
|
||||
switch(lowercaseLetter) {
|
||||
case "a":
|
||||
console.log("A");
|
||||
break;
|
||||
case "b":
|
||||
console.log("B");
|
||||
break;
|
||||
}
|
||||
```
|
||||
|
||||
I valori `case` vengono testati con uguaglianza stretta (`===`). Il `break` dice a JavaScript di interrompere l'esecuzione delle istruzioni. Se il `break` viene omesso, sarà eseguita la successiva istruzione.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Scrivi una dichiarazione switch che testa `val` e imposta il valore di `answer` per le seguenti condizioni:
|
||||
`1` - `alpha`
|
||||
`2` - `beta`
|
||||
`3` - `gamma`
|
||||
`4` - `delta`
|
||||
|
||||
# --hints--
|
||||
|
||||
`caseInSwitch(1)` dovrebbe avere il valore stringa `alpha`
|
||||
|
||||
```js
|
||||
assert(caseInSwitch(1) === 'alpha');
|
||||
```
|
||||
|
||||
`caseInSwitch(2)` dovrebbe avere il valore stringa `beta`
|
||||
|
||||
```js
|
||||
assert(caseInSwitch(2) === 'beta');
|
||||
```
|
||||
|
||||
`caseInSwitch(3)` dovrebbe avere il valore stringa `gamma`
|
||||
|
||||
```js
|
||||
assert(caseInSwitch(3) === 'gamma');
|
||||
```
|
||||
|
||||
`caseInSwitch(4)` dovrebbe avere il valore stringa `delta`
|
||||
|
||||
```js
|
||||
assert(caseInSwitch(4) === 'delta');
|
||||
```
|
||||
|
||||
Non dovresti usare alcuna dichiarazione `if` o `else`
|
||||
|
||||
```js
|
||||
assert(!/else/g.test(code) || !/if/g.test(code));
|
||||
```
|
||||
|
||||
Dovresti avere almeno 3 istruzioni `break`
|
||||
|
||||
```js
|
||||
assert(code.match(/break/g).length > 2);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function caseInSwitch(val) {
|
||||
var answer = "";
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
return answer;
|
||||
}
|
||||
|
||||
caseInSwitch(1);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function caseInSwitch(val) {
|
||||
var answer = "";
|
||||
|
||||
switch(val) {
|
||||
case 1:
|
||||
answer = "alpha";
|
||||
break;
|
||||
case 2:
|
||||
answer = "beta";
|
||||
break;
|
||||
case 3:
|
||||
answer = "gamma";
|
||||
break;
|
||||
case 4:
|
||||
answer = "delta";
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
```
|
@ -0,0 +1,97 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244bc
|
||||
title: Lista della spesa
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9MEKHZ'
|
||||
forumTopicId: 18280
|
||||
dashedName: shopping-list
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Crea una lista della spesa nella variabile `myList`. L'elenco dovrebbe essere un array multidimensionale contenente diversi sotto-array.
|
||||
|
||||
Il primo elemento in ogni sotto-array dovrebbe contenere una stringa con il nome dell'elemento. Il secondo elemento dovrebbe essere un numero che rappresenta la quantità, per esempio
|
||||
|
||||
```js
|
||||
["Chocolate Bar", 15]
|
||||
```
|
||||
|
||||
Ci dovrebbero essere almeno 5 sotto-array nella lista.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myList` dovrebbe essere un array.
|
||||
|
||||
```js
|
||||
assert(isArray);
|
||||
```
|
||||
|
||||
Il primo elemento in ciascuno dei sotto-array dovrebbe essere una stringa.
|
||||
|
||||
```js
|
||||
assert(hasString);
|
||||
```
|
||||
|
||||
Il secondo elemento in ciascuno dei sotto-array dovrebbe essere un numero.
|
||||
|
||||
```js
|
||||
assert(hasNumber);
|
||||
```
|
||||
|
||||
Dovresti avere almeno 5 articoli nella lista.
|
||||
|
||||
```js
|
||||
assert(count > 4);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
var count = 0;
|
||||
var isArray = false;
|
||||
var hasString = false;
|
||||
var hasNumber = false;
|
||||
(function(list){
|
||||
if(Array.isArray(myList)) {
|
||||
isArray = true;
|
||||
if(myList.length > 0) {
|
||||
hasString = true;
|
||||
hasNumber = true;
|
||||
for (var elem of myList) {
|
||||
if(!elem || !elem[0] || typeof elem[0] !== 'string') {
|
||||
hasString = false;
|
||||
}
|
||||
if(!elem || typeof elem[1] !== 'number') {
|
||||
hasNumber = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
count = myList.length;
|
||||
return JSON.stringify(myList);
|
||||
} else {
|
||||
return "myList is not an array";
|
||||
}
|
||||
|
||||
})(myList);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myList = [];
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myList = [
|
||||
["Candy", 10],
|
||||
["Potatoes", 12],
|
||||
["Eggs", 12],
|
||||
["Catfood", 1],
|
||||
["Toads", 9]
|
||||
];
|
||||
```
|
@ -0,0 +1,118 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c6
|
||||
title: Stare in fila
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8Q8tP'
|
||||
forumTopicId: 18307
|
||||
dashedName: stand-in-line
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In Informatica una <dfn>coda</dfn> (queue) è una <dfn>struttura di dati</dfn> astratta dove gli elementi sono tenuti in ordine. I nuovi elementi possono essere aggiunti alla fine della coda e quelli vecchi vengono rimossi dall'inizio della coda.
|
||||
|
||||
Scrivi una funzione `nextInLine` che prende un array (`arr`) e un numero (`item`) come argomenti.
|
||||
|
||||
Aggiungi il numero alla fine dell'array, quindi rimuovi il primo elemento dell'array.
|
||||
|
||||
La funzione `nextInLine` dovrebbe quindi restituire l'elemento rimosso.
|
||||
|
||||
# --hints--
|
||||
|
||||
`nextInLine([], 5)` dovrebbe restituire un numero.
|
||||
|
||||
```js
|
||||
assert.isNumber(nextInLine([], 5));
|
||||
```
|
||||
|
||||
`nextInLine([], 1)` dovrebbe restituire `1`
|
||||
|
||||
```js
|
||||
assert(nextInLine([], 1) === 1);
|
||||
```
|
||||
|
||||
`nextInLine([2], 1)` dovrebbe restituire `2`
|
||||
|
||||
```js
|
||||
assert(nextInLine([2], 1) === 2);
|
||||
```
|
||||
|
||||
`nextInLine([5,6,7,8,9], 1)` dovrebbe restituire `5`
|
||||
|
||||
```js
|
||||
assert(nextInLine([5, 6, 7, 8, 9], 1) === 5);
|
||||
```
|
||||
|
||||
Dopo la chiamata di `nextInLine(testArr, 10)`, `testArr[4]` dovrebbe valere `10`
|
||||
|
||||
```js
|
||||
nextInLine(testArr, 10);
|
||||
assert(testArr[4] === 10);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
var logOutput = [];
|
||||
var originalConsole = console
|
||||
function capture() {
|
||||
var nativeLog = console.log;
|
||||
console.log = function (message) {
|
||||
logOutput.push(message);
|
||||
if(nativeLog.apply) {
|
||||
nativeLog.apply(originalConsole, arguments);
|
||||
} else {
|
||||
var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');
|
||||
nativeLog(nativeMsg);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function uncapture() {
|
||||
console.log = originalConsole.log;
|
||||
}
|
||||
|
||||
capture();
|
||||
```
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
uncapture();
|
||||
testArr = [1,2,3,4,5];
|
||||
(function() { return logOutput.join("\n");})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function nextInLine(arr, item) {
|
||||
// Only change code below this line
|
||||
|
||||
return item;
|
||||
// Only change code above this line
|
||||
|
||||
|
||||
}
|
||||
|
||||
// Setup
|
||||
var testArr = [1,2,3,4,5];
|
||||
|
||||
// Display code
|
||||
console.log("Before: " + JSON.stringify(testArr));
|
||||
console.log(nextInLine(testArr, 6));
|
||||
console.log("After: " + JSON.stringify(testArr));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var testArr = [ 1,2,3,4,5];
|
||||
|
||||
function nextInLine(arr, item) {
|
||||
arr.push(item);
|
||||
return arr.shift();
|
||||
}
|
||||
```
|
@ -0,0 +1,63 @@
|
||||
---
|
||||
id: bd7993c9c69feddfaeb8bdef
|
||||
title: Memorizzare più valori in una variabile utilizzando gli array in JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/crZQWAm'
|
||||
forumTopicId: 18309
|
||||
dashedName: store-multiple-values-in-one-variable-using-javascript-arrays
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Con le variabili `array` di JavaScript, possiamo memorizzare diversi dati in un unico posto.
|
||||
|
||||
La dichiarazione di un array inizia con una parentesi quadra di apertura, e termina con una parentesi quadra di chiusura, con gli elementi separati da virgole, in questo modo:
|
||||
|
||||
```js
|
||||
var sandwich = ["peanut butter", "jelly", "bread"]
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modifica il nuovo array `myArray` in modo che contenga sia una stringa che un numero (in quest'ordine).
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` dovrebbe essere un array.
|
||||
|
||||
```js
|
||||
assert(typeof myArray == 'object');
|
||||
```
|
||||
|
||||
Il primo elemento in `myArray` dovrebbe essere una stringa.
|
||||
|
||||
```js
|
||||
assert(typeof myArray[0] !== 'undefined' && typeof myArray[0] == 'string');
|
||||
```
|
||||
|
||||
Il secondo elemento in `myArray` dovrebbe essere un numero.
|
||||
|
||||
```js
|
||||
assert(typeof myArray[1] !== 'undefined' && typeof myArray[1] == 'number');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return z;})(myArray);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
var myArray = [];
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = ["The Answer", 42];
|
||||
```
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244a8
|
||||
title: Memorizzare valori con l'operatore di assegnazione
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cEanysE'
|
||||
forumTopicId: 18310
|
||||
dashedName: storing-values-with-the-assignment-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, puoi memorizzare un valore in una variabile con l'operatore <dfn>di assegnazione</dfn> (`=`).
|
||||
|
||||
```js
|
||||
myVariable = 5;
|
||||
```
|
||||
|
||||
Questo assegna il valore `Number` `5` a `myVariable`.
|
||||
|
||||
Se sono presenti calcoli a destra dell'operatore `=`, vengono eseguiti prima che il valore venga assegnato alla variabile a sinistra dell'operatore.
|
||||
|
||||
```js
|
||||
var myVar;
|
||||
myVar = 5;
|
||||
```
|
||||
|
||||
Innanzitutto, questo codice crea una variabile denominata `myVar`. Quindi, il codice assegna `5` a `myVar`. Ora, se `myVar` appare di nuovo nel codice, il programma lo tratterà come se fosse `5`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Assegna il valore `7` alla variabile `a`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Non modificare il codice sopra il commento specificato.
|
||||
|
||||
```js
|
||||
assert(/var a;/.test(code));
|
||||
```
|
||||
|
||||
`a` dovrebbe avere un valore di 7.
|
||||
|
||||
```js
|
||||
assert(typeof a === 'number' && a === 7);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
if (typeof a != 'undefined') {
|
||||
a = undefined;
|
||||
}
|
||||
```
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a){return "a = " + a;})(a);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var a;
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a;
|
||||
a = 7;
|
||||
```
|
@ -0,0 +1,59 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb4bdef
|
||||
title: Sottrarre un numero da un altro con JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cP3yQtk'
|
||||
forumTopicId: 18314
|
||||
dashedName: subtract-one-number-from-another-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Possiamo anche sottrarre un numero da un altro.
|
||||
|
||||
JavaScript utilizza il simbolo `-` per la sottrazione.
|
||||
|
||||
**Esempio**
|
||||
|
||||
```js
|
||||
myVar = 12 - 6;
|
||||
```
|
||||
|
||||
`myVar` avrà il valore `6`.
|
||||
# --instructions--
|
||||
|
||||
Modifica lo `0` in modo che la differenza sia `12`.
|
||||
|
||||
# --hints--
|
||||
|
||||
La variabile `difference` dovrebbe essere uguale a 12.
|
||||
|
||||
```js
|
||||
assert(difference === 12);
|
||||
```
|
||||
|
||||
Devi solo sottrarre un numero da 45.
|
||||
|
||||
```js
|
||||
assert(/difference=45-33;?/.test(__helpers.removeWhiteSpace(code)));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'difference = '+z;})(difference);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var difference = 45 - 0;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var difference = 45 - 33;
|
||||
```
|
@ -0,0 +1,98 @@
|
||||
---
|
||||
id: 567af2437cbaa8c51670a16c
|
||||
title: Verificare la presenza delle proprietà degli oggetti
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c6Wz4ySr'
|
||||
forumTopicId: 18324
|
||||
dashedName: testing-objects-for-properties
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A volte è utile verificare se la proprietà di un dato oggetto esiste o meno. Possiamo usare il metodo `.hasOwnProperty(propname)` degli oggetti per determinare se quell'oggetto ha una proprietà con quel nome. `.hasOwnProperty()` restituisce `true` o `false` se la proprietà viene trovata o meno.
|
||||
|
||||
**Esempio**
|
||||
|
||||
```js
|
||||
var myObj = {
|
||||
top: "hat",
|
||||
bottom: "pants"
|
||||
};
|
||||
myObj.hasOwnProperty("top");
|
||||
myObj.hasOwnProperty("middle");
|
||||
```
|
||||
|
||||
Il primo `hasOwnProperty` restituisce `true`, mentre il secondo restituisce `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modifica la funzione `checkObj` per verificare se un oggetto passato alla funzione (`obj`) contiene una proprietà specifica (`checkProp`). Se la proprietà viene trovata, restituisci il valore di quella proprietà. In caso contrario, restituisci `"Not Found"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")` dovrebbe restituire la stringa `pony`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
checkObj({ gift: 'pony', pet: 'kitten', bed: 'sleigh' }, 'gift') === 'pony'
|
||||
);
|
||||
```
|
||||
|
||||
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet")` dovrebbe restituire la stringa `kitten`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
checkObj({ gift: 'pony', pet: 'kitten', bed: 'sleigh' }, 'pet') === 'kitten'
|
||||
);
|
||||
```
|
||||
|
||||
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house")` dovrebbe restituire la stringa `Not Found`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
checkObj({ gift: 'pony', pet: 'kitten', bed: 'sleigh' }, 'house') ===
|
||||
'Not Found'
|
||||
);
|
||||
```
|
||||
|
||||
`checkObj({city: "Seattle"}, "city")` dovrebbe restituire la stringa `Seattle`.
|
||||
|
||||
```js
|
||||
assert(checkObj({ city: 'Seattle' }, 'city') === 'Seattle');
|
||||
```
|
||||
|
||||
`checkObj({city: "Seattle"}, "district")` dovrebbe restituire la stringa `Not Found`.
|
||||
|
||||
```js
|
||||
assert(checkObj({ city: 'Seattle' }, 'district') === 'Not Found');
|
||||
```
|
||||
|
||||
`checkObj({pet: "kitten", bed: "sleigh"}, "gift")` dovrebbe restituire la stringa `Not Found`.
|
||||
|
||||
```js
|
||||
assert(checkObj({ pet: 'kitten', bed: 'sleigh' }, 'gift') === 'Not Found');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function checkObj(obj, checkProp) {
|
||||
// Only change code below this line
|
||||
return "Change Me!";
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function checkObj(obj, checkProp) {
|
||||
if(obj.hasOwnProperty(checkProp)) {
|
||||
return obj[checkProp];
|
||||
} else {
|
||||
return "Not Found";
|
||||
}
|
||||
}
|
||||
```
|
@ -0,0 +1,70 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ba
|
||||
title: Comprendere l'immutabilità delle stringhe
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWPVaUR'
|
||||
forumTopicId: 18331
|
||||
dashedName: understand-string-immutability
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, le stringhe (`String`) sono <dfn>immutabili</dfn>, il che significa che non possono essere modificate una volta create.
|
||||
|
||||
Ad esempio, il codice seguente:
|
||||
|
||||
```js
|
||||
var myStr = "Bob";
|
||||
myStr[0] = "J";
|
||||
```
|
||||
|
||||
non può modificare il valore di `myStr` in `Job`, poiché il contenuto di `myStr` non può essere modificato. Tieni presente che questo *non* significa che `myStr` non può essere modificato, ma solo che i singoli caratteri di una <dfn>stringa letterale</dfn> non possono essere cambiati. L'unico modo per modificare `myStr` è di assegnargli una nuova stringa, in questo modo:
|
||||
|
||||
```js
|
||||
var myStr = "Bob";
|
||||
myStr = "Job";
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Correggi l'assegnazione a `myStr` in modo che contenga il valore stringa di `Hello World` utilizzando l'approccio mostrato nell'esempio sopra.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr` dovrebbe avere un valore stringa `Hello World`.
|
||||
|
||||
```js
|
||||
assert(myStr === 'Hello World');
|
||||
```
|
||||
|
||||
Non modificare il codice sopra il commento specificato.
|
||||
|
||||
```js
|
||||
assert(/myStr = "Jello World"/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(v){return "myStr = " + v;})(myStr);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myStr = "Jello World";
|
||||
|
||||
// Only change code below this line
|
||||
myStr[0] = "H"; // Change this line
|
||||
// Only change code above this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "Jello World";
|
||||
myStr = "Hello World";
|
||||
```
|
@ -0,0 +1,61 @@
|
||||
---
|
||||
id: bd7123c9c441eddfaeb5bdef
|
||||
title: Comprendere i valori booleani
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9Me8t4'
|
||||
forumTopicId: 301176
|
||||
dashedName: understanding-boolean-values
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Un altro tipo di dati è il <dfn>Boolean</dfn>. I valori booleani possono essere solo uno di due valori: `true` o `false`. Sono fondamentalmente piccoli interruttori on-off, dove `true` è attivato e `false` è disattivato. Questi due stati si escludono a vicenda.
|
||||
|
||||
**Nota:** i valori booleani non vengono mai scritti tra virgolette. Le stringhe `"true"` e `"false"` non sono booleane e non hanno alcun significato speciale in JavaScript.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modifica la funzione `welcomeToBooleans` in modo che restituisca `true` invece di `false` quando si fa clic sul pulsante per eseguire.
|
||||
|
||||
# --hints--
|
||||
|
||||
La funzione `welcomeToBooleans()` dovrebbe restituire un valore booleano (`true` o `false`).
|
||||
|
||||
```js
|
||||
assert(typeof welcomeToBooleans() === 'boolean');
|
||||
```
|
||||
|
||||
`welcomeToBooleans()` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert(welcomeToBooleans() === true);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
welcomeToBooleans();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function welcomeToBooleans() {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
return false; // Change this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function welcomeToBooleans() {
|
||||
return true; // Change this line
|
||||
}
|
||||
```
|
@ -0,0 +1,100 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ab
|
||||
title: Comprendere la distinzione tra maiuscole e minuscole nelle variabili
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cd6GDcD'
|
||||
forumTopicId: 18334
|
||||
dashedName: understanding-case-sensitivity-in-variables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript tutte le variabili e i nomi delle funzioni fanno distinzione tra maiuscole e minuscole. Ciò significa che la capitalizzazione è importante.
|
||||
|
||||
`MYVAR` non è uguale a `MyVar` né a `myvar`. È possibile avere più variabili distinte con lo stesso nome ma con un diverso uso delle maiuscole. Si consiglia vivamente di *non* utilizzare questa funzionalità del linguaggio per motivi di chiarezza.
|
||||
|
||||
**Buona pratica**
|
||||
|
||||
Scrivi i nomi delle variabili in JavaScript in <dfn>camelCase</dfn>. In <dfn>camelCase</dfn>, i nomi delle variabili composti da più parole hanno la prima parola in minuscolo e la prima lettera di ogni parola successiva in maiuscolo.
|
||||
|
||||
**Esempi:**
|
||||
|
||||
```js
|
||||
var someVariable;
|
||||
var anotherVariableName;
|
||||
var thisVariableNameIsSoLong;
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modifica le dichiarazioni e le assegnazioni esistenti in modo che i loro nomi utilizzino <dfn>camelCase</dfn>.
|
||||
|
||||
Non creare nuove variabili.
|
||||
|
||||
# --hints--
|
||||
|
||||
`studlyCapVar` dovrebbe essere definito e avere un valore di `10`.
|
||||
|
||||
```js
|
||||
assert(typeof studlyCapVar !== 'undefined' && studlyCapVar === 10);
|
||||
```
|
||||
|
||||
`ProperCamelCase` dovrebbe essere definito e avere un valore della stringa `A String`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
typeof properCamelCase !== 'undefined' && properCamelCase === 'A String'
|
||||
);
|
||||
```
|
||||
|
||||
`titleCaseOver` dovrebbe essere definito e avere un valore di `9000`.
|
||||
|
||||
```js
|
||||
assert(typeof titleCaseOver !== 'undefined' && titleCaseOver === 9000);
|
||||
```
|
||||
|
||||
`studlyCapVar` dovrebbe usare camelCase sia nella sezione di dichiarazione che in quella di assegnazione.
|
||||
|
||||
```js
|
||||
assert(code.match(/studlyCapVar/g).length === 2);
|
||||
```
|
||||
|
||||
`properCamelCase` dovrebbe usare camelCase sia nella sezione di dichiarazione che in quella di assegnazione.
|
||||
|
||||
```js
|
||||
assert(code.match(/properCamelCase/g).length === 2);
|
||||
```
|
||||
|
||||
`titleCaseOver` dovrebbe usare camelCase sia nella sezione di dichiarazione che in quella di assegnazione.
|
||||
|
||||
```js
|
||||
assert(code.match(/titleCaseOver/g).length === 2);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Variable declarations
|
||||
var StUdLyCapVaR;
|
||||
var properCamelCase;
|
||||
var TitleCaseOver;
|
||||
|
||||
// Variable assignments
|
||||
STUDLYCAPVAR = 10;
|
||||
PRoperCAmelCAse = "A String";
|
||||
tITLEcASEoVER = 9000;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var studlyCapVar;
|
||||
var properCamelCase;
|
||||
var titleCaseOver;
|
||||
|
||||
studlyCapVar = 10;
|
||||
properCamelCase = "A String";
|
||||
titleCaseOver = 9000;
|
||||
```
|
@ -0,0 +1,94 @@
|
||||
---
|
||||
id: 598e8944f009e646fc236146
|
||||
title: Comprendere il valore undefined restituito da una funzione
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ce2p7cL'
|
||||
forumTopicId: 301177
|
||||
dashedName: understanding-undefined-value-returned-from-a-function
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Una funzione può includere l'istruzione `return` ma questa non deve essere necessariamente inclusa. Nel caso in cui la funzione non abbia un'istruzione `return`, quando la chiami, la funzione elabora il codice interno ma il valore restituito è `undefined`.
|
||||
|
||||
**Esempio**
|
||||
|
||||
```js
|
||||
var sum = 0;
|
||||
function addSum(num) {
|
||||
sum = sum + num;
|
||||
}
|
||||
addSum(3);
|
||||
```
|
||||
|
||||
`addSum` è una funzione senza un'istruzione `return`. La funzione cambierà la variabile globale `sum` ma il valore restituito dalla funzione sarà `undefined`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Crea una funzione `addFive` senza argomenti. Questa funzione aggiunge 5 alla variabile `sum`, ma il valore restituito è `undefined`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`addFive` dovrebbe essere una funzione.
|
||||
|
||||
```js
|
||||
assert(typeof addFive === 'function');
|
||||
```
|
||||
|
||||
Una volta che entrambe le funzioni saranno state eseguite, `sum` dovrebbe essere uguale a `8`.
|
||||
|
||||
```js
|
||||
assert(sum === 8);
|
||||
```
|
||||
|
||||
Il valore restituito da `addFive` dovrebbe essere `undefined`.
|
||||
|
||||
```js
|
||||
assert(addFive() === undefined);
|
||||
```
|
||||
|
||||
All'interno della funzione `addFive`, dovresti aggiungere `5` alla variabile `sum`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
__helpers.removeWhiteSpace(addFive.toString()).match(/sum=sum\+5|sum\+=5/)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var sum = 0;
|
||||
|
||||
function addThree() {
|
||||
sum = sum + 3;
|
||||
}
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
addThree();
|
||||
addFive();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var sum = 0;
|
||||
|
||||
function addThree() {
|
||||
sum = sum + 3;
|
||||
}
|
||||
|
||||
function addFive() {
|
||||
sum = sum + 5;
|
||||
}
|
||||
|
||||
addThree();
|
||||
addFive();
|
||||
```
|
@ -0,0 +1,79 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244aa
|
||||
title: Comprendere le variabili non inizializzate
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBa2JAL'
|
||||
forumTopicId: 18335
|
||||
dashedName: understanding-uninitialized-variables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Quando vengono dichiarate variabili JavaScript, esse hanno un valore iniziale `undefined`. Se esegui un'operazione matematica su una variabile `undefined`, il risultato sarà `NaN` che significa <dfn>"Not a Number"</dfn> (Non un numero). Se concateni una stringa con una variabile `undefined`, otterrai una <dfn>stringa</dfn> letterale `undefined`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Inizializza le tre variabili `a`, `b` e `c` con `5`, `10`, e `"I am a"` rispettivamente, in modo che non siano `undefined`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` dovrebbe essere definito e avere il valore `6`.
|
||||
|
||||
```js
|
||||
assert(typeof a === 'number' && a === 6);
|
||||
```
|
||||
|
||||
`b` dovrebbe essere definito e avere il valore `15`.
|
||||
|
||||
```js
|
||||
assert(typeof b === 'number' && b === 15);
|
||||
```
|
||||
|
||||
`c` non dovrebbe contenere `undefined` e dovrebbe avere un valore stringa `I am a String!`
|
||||
|
||||
```js
|
||||
assert(!/undefined/.test(c) && c === 'I am a String!');
|
||||
```
|
||||
|
||||
Non modificare il codice sotto il commento specificato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/a = a \+ 1;/.test(code) &&
|
||||
/b = b \+ 5;/.test(code) &&
|
||||
/c = c \+ " String!";/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = '" + c + "'"; })(a,b,c);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
var a;
|
||||
var b;
|
||||
var c;
|
||||
// Only change code above this line
|
||||
|
||||
a = a + 1;
|
||||
b = b + 5;
|
||||
c = c + " String!";
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 5;
|
||||
var b = 10;
|
||||
var c = "I am a";
|
||||
a = a + 1;
|
||||
b = b + 5;
|
||||
c = c + " String!";
|
||||
```
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d1
|
||||
title: Aggiornare le proprietà di un oggetto
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9yEJT4'
|
||||
forumTopicId: 18336
|
||||
dashedName: updating-object-properties
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Dopo aver creato un oggetto JavaScript, è possibile aggiornare le sue proprietà in qualsiasi momento proprio come quando si aggiorna qualsiasi altra variabile. Per aggiornare le proprietà è possibile utilizzare la notazione a punti o a parentesi.
|
||||
|
||||
Ad esempio, diamo un'occhiata a `ourDog`:
|
||||
|
||||
```js
|
||||
var ourDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"]
|
||||
};
|
||||
```
|
||||
|
||||
Dal momento che è un cane particolarmente felice, cambiamo il suo nome nella stringa `Happy Camper`. Ecco come aggiorniamo la proprietà del nome del suo oggetto: `ourDog.name = "Happy Camper";` o `ourDog["name"] = "Happy Camper";` Adesso quando valutiamo `ourDog.name`, invece di ottenere `Camper`, otterremo il suo nuovo nome, `Happy Camper`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Aggiorna la proprietà nome dell'oggetto `myDog`. Cambia il suo nome da `Coder` a `Happy Coder`. È possibile utilizzare la notazione a punti o a parentesi per aggiornare.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti aggiornare la proprietà di `myDog` denominata `name`per assegnarle la stringa `Happy Coder`.
|
||||
|
||||
```js
|
||||
assert(/happy coder/gi.test(myDog.name));
|
||||
```
|
||||
|
||||
Non dovresti modificare la definizione di `myDog`.
|
||||
|
||||
```js
|
||||
assert(/"name": "Coder"/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return z;})(myDog);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myDog = {
|
||||
"name": "Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"]
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
"name": "Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"]
|
||||
};
|
||||
myDog.name = "Happy Coder";
|
||||
```
|
@ -0,0 +1,74 @@
|
||||
---
|
||||
id: bd7123c9c549eddfaeb5bdef
|
||||
title: Usare la notazione a parentesi per trovare il primo carattere in una stringa
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8JwhW'
|
||||
forumTopicId: 18341
|
||||
dashedName: use-bracket-notation-to-find-the-first-character-in-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>La notazione a parentesi</dfn> è un modo per ottenere il carattere a un indice specifico all'interno di una stringa.
|
||||
|
||||
La maggior parte dei moderni linguaggi di programmazione, come JavaScript, non inizia a contare da 1 come gli esseri umani. Loro iniziano dallo 0. Questo è indicato come indicizzazione <dfn>Zero-based</dfn>.
|
||||
|
||||
Ad esempio, il carattere all'indice 0 nella parola `Charles` è `C`. Quindi, se `var firstName = "Charles"`, è possibile ottenere il valore della prima lettera della stringa utilizzando `firstName[0]`.
|
||||
|
||||
Esempio:
|
||||
|
||||
```js
|
||||
var firstName = "Charles";
|
||||
var firstLetter = firstName[0];
|
||||
```
|
||||
|
||||
`firstLetter` dovrebbe avere un valore stringa `C`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa la notazione parentesi per trovare il primo carattere nella variabile `lastName` e assegnala a `firstLetterOfLastName`.
|
||||
|
||||
**Suggerimento:** Prova a guardare l'esempio qui sopra se sei bloccato.
|
||||
|
||||
# --hints--
|
||||
|
||||
La variabile `firstLetterOfLastName` dovrebbe avere il valore di `L`.
|
||||
|
||||
```js
|
||||
assert(firstLetterOfLastName === 'L');
|
||||
```
|
||||
|
||||
Dovresti usare la notazione a parentesi.
|
||||
|
||||
```js
|
||||
assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(v){return v;})(firstLetterOfLastName);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var firstLetterOfLastName = "";
|
||||
var lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
firstLetterOfLastName = lastName; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var firstLetterOfLastName = "";
|
||||
var lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
firstLetterOfLastName = lastName[0];
|
||||
```
|
@ -0,0 +1,68 @@
|
||||
---
|
||||
id: bd7123c9c451eddfaeb5bdef
|
||||
title: Usare la notazione a parentesi per trovare l'ultimo carattere in una stringa
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBZQGcv'
|
||||
forumTopicId: 18342
|
||||
dashedName: use-bracket-notation-to-find-the-last-character-in-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Al fine di ottenere l'ultima lettera di una stringa, è possibile sottrarre uno dalla lunghezza della stringa.
|
||||
|
||||
Per esempio, se `var firstName = "Ada"`, puoi ottenere il valore dell'ultima lettera della stringa usando `firstName[firstName.length - 1]`.
|
||||
|
||||
Esempio:
|
||||
|
||||
```js
|
||||
var firstName = "Ada";
|
||||
var lastLetter = firstName[firstName.length - 1];
|
||||
```
|
||||
|
||||
`lastLetter` dovrebbe avere un valore stringa `a`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa <dfn>la notazione a parentesi</dfn> per trovare l'ultimo carattere nella variabile `lastName`.
|
||||
|
||||
**Suggerimento:** Prova a guardare l'esempio qui sopra se sei bloccato.
|
||||
|
||||
# --hints--
|
||||
|
||||
`lastLetterOfLastName` dovrebbe essere la lettera `e`.
|
||||
|
||||
```js
|
||||
assert(lastLetterOfLastName === 'e');
|
||||
```
|
||||
|
||||
Dovresti usare `.length` per ottenere l'ultima lettera.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.length/g).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(v){return v;})(lastLetterOfLastName);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
var lastLetterOfLastName = lastName; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastName = "Lovelace";
|
||||
var lastLetterOfLastName = lastName[lastName.length - 1];
|
||||
```
|
@ -0,0 +1,68 @@
|
||||
---
|
||||
id: bd7123c9c450eddfaeb5bdef
|
||||
title: Usare la notazione parentesi per trovare l'n-esimo carattere in una stringa
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWPVJua'
|
||||
forumTopicId: 18343
|
||||
dashedName: use-bracket-notation-to-find-the-nth-character-in-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Puoi usare <dfn>la notazione a parentesi</dfn> anche per ottenere il carattere in altre posizioni all'interno di una stringa.
|
||||
|
||||
Ricorda che i computer iniziano a contare da `0`, quindi il primo carattere è in realtà il carattere zero.
|
||||
|
||||
Esempio:
|
||||
|
||||
```js
|
||||
var firstName = "Ada";
|
||||
var secondLetterOfFirstName = firstName[1];
|
||||
```
|
||||
|
||||
`secondLetterOfFirstName` dovrebbe acere un valore stringa `d`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Cerchiamo di impostare `thirdLetterOfLastName` per eguagliare la terza lettera della variabile `lastName` usando la notazione parentesi.
|
||||
|
||||
**Suggerimento:** Prova a guardare l'esempio qui sopra se ti blocchi.
|
||||
|
||||
# --hints--
|
||||
|
||||
La variabile `thirdLetterOfLastName` dovrebbe avere il valore di `v`.
|
||||
|
||||
```js
|
||||
assert(thirdLetterOfLastName === 'v');
|
||||
```
|
||||
|
||||
Dovresti usare la notazione a parentesi.
|
||||
|
||||
```js
|
||||
assert(code.match(/thirdLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(v){return v;})(thirdLetterOfLastName);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
var thirdLetterOfLastName = lastName; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastName = "Lovelace";
|
||||
var thirdLetterOfLastName = lastName[2];
|
||||
```
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user