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,97 @@
|
||||
---
|
||||
id: a77dbc43c33f39daa4429b4f
|
||||
title: Boo who
|
||||
challengeType: 5
|
||||
forumTopicId: 16000
|
||||
dashedName: boo-who
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Controllare se un valore è un classificato come primitivo booleano. Restituisce `true` o `false`.
|
||||
|
||||
I primitivi booleani sono `true` e `false`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`booWho(true)` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(true), true);
|
||||
```
|
||||
|
||||
`booWho(false)` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(false), true);
|
||||
```
|
||||
|
||||
`booWho([1, 2, 3])` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho([1, 2, 3]), false);
|
||||
```
|
||||
|
||||
`booWho([].slice)` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho([].slice), false);
|
||||
```
|
||||
|
||||
`booWho({ "a": 1 })` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho({ a: 1 }), false);
|
||||
```
|
||||
|
||||
`booWho(1)` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(1), false);
|
||||
```
|
||||
|
||||
`booWho(NaN)` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(NaN), false);
|
||||
```
|
||||
|
||||
`booWho("a")` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho('a'), false);
|
||||
```
|
||||
|
||||
`booWho("true")` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho('true'), false);
|
||||
```
|
||||
|
||||
`booWho("false")` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho('false'), false);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function booWho(bool) {
|
||||
return bool;
|
||||
}
|
||||
|
||||
booWho(null);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function booWho(bool) {
|
||||
return typeof bool === "boolean";
|
||||
}
|
||||
|
||||
booWho(null);
|
||||
```
|
@ -0,0 +1,110 @@
|
||||
---
|
||||
id: a9bd25c716030ec90084d8a1
|
||||
title: Chunky Monkey
|
||||
challengeType: 5
|
||||
forumTopicId: 16005
|
||||
dashedName: chunky-monkey
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Scrivi una funzione che divida un array (primo argomento) in gruppi di lunghezza pari a `size` (secondo argomento) e li restituisca come un array bidimensionale.
|
||||
|
||||
# --hints--
|
||||
|
||||
`chunkArrayInGroups(["a", "b", "c", "d"], 2)` deve restituire `[["a", "b"], ["c", "d"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2), [
|
||||
['a', 'b'],
|
||||
['c', 'd']
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)` deve restituire `[[0, 1, 2], [3, 4, 5]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3), [
|
||||
[0, 1, 2],
|
||||
[3, 4, 5]
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)` deve restituire `[[0, 1], [2, 3], [4, 5]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2), [
|
||||
[0, 1],
|
||||
[2, 3],
|
||||
[4, 5]
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)` deve restituire `[[0, 1, 2, 3], [4, 5]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4), [
|
||||
[0, 1, 2, 3],
|
||||
[4, 5]
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)` deve restituire `[[0, 1, 2], [3, 4, 5], [6]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3), [
|
||||
[0, 1, 2],
|
||||
[3, 4, 5],
|
||||
[6]
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)` deve restituire `[[0, 1, 2, 3], [4, 5, 6, 7], [8]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4), [
|
||||
[0, 1, 2, 3],
|
||||
[4, 5, 6, 7],
|
||||
[8]
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)` deve restituire `[[0, 1], [2, 3], [4, 5], [6, 7], [8]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2), [
|
||||
[0, 1],
|
||||
[2, 3],
|
||||
[4, 5],
|
||||
[6, 7],
|
||||
[8]
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function chunkArrayInGroups(arr, size) {
|
||||
return arr;
|
||||
}
|
||||
|
||||
chunkArrayInGroups(["a", "b", "c", "d"], 2);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function chunkArrayInGroups(arr, size) {
|
||||
let out = [];
|
||||
|
||||
for (let i = 0; i < arr.length; i += size) {
|
||||
out.push(arr.slice(i, i + size));
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
chunkArrayInGroups(["a", "b", "c", "d"], 2);
|
||||
```
|
@ -0,0 +1,113 @@
|
||||
---
|
||||
id: acda2fb1324d9b0fa741e6b5
|
||||
title: Confermare la finale
|
||||
challengeType: 5
|
||||
forumTopicId: 16006
|
||||
dashedName: confirm-the-ending
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Verifica se una stringa (primo argomento, `str`) finisce con la stringa data (secondo argomento, `target`).
|
||||
|
||||
Questa sfida *può essere risolta* con il metodo `.endsWith()`, che è stato introdotto in ES2015. Tuttavia, per lo scopo di questa sfida, vorremmo che tu usassi uno dei metodi di sottostringa di JavaScript.
|
||||
|
||||
# --hints--
|
||||
|
||||
`confirmEnding("Bastian", "n")` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Bastian', 'n') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Congratulation", "on")` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Congratulation', 'on') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Connor", "n")` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Connor', 'n') === false);
|
||||
```
|
||||
|
||||
`confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification")` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
confirmEnding(
|
||||
'Walking on water and developing software from a specification are easy if both are frozen',
|
||||
'specification'
|
||||
) === false
|
||||
);
|
||||
```
|
||||
|
||||
`confirmEnding("He has to give me a new name", "name")` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('He has to give me a new name', 'name') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Open sesame", "same")` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Open sesame', 'same') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Open sesame", "sage")` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Open sesame', 'sage') === false);
|
||||
```
|
||||
|
||||
`confirmEnding("Open sesame", "game")` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Open sesame', 'game') === false);
|
||||
```
|
||||
|
||||
`confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
confirmEnding(
|
||||
'If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing',
|
||||
'mountain'
|
||||
) === false
|
||||
);
|
||||
```
|
||||
|
||||
`confirmEnding("Abstraction", "action")` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Abstraction', 'action') === true);
|
||||
```
|
||||
|
||||
Il tuo codice non dovrebbe utilizzare il metodo integrato `.endsWith()` per risolvere la sfida.
|
||||
|
||||
```js
|
||||
assert(!/\.endsWith\(.*?\)\s*?;?/.test(code) && !/\['endsWith'\]/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function confirmEnding(str, target) {
|
||||
return str;
|
||||
}
|
||||
|
||||
confirmEnding("Bastian", "n");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function confirmEnding(str, target) {
|
||||
return str.substring(str.length - target.length) === target;
|
||||
}
|
||||
|
||||
confirmEnding("Bastian", "n");
|
||||
```
|
@ -0,0 +1,76 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b3
|
||||
title: Convertire i gradi Celsius in Fahrenheit
|
||||
challengeType: 1
|
||||
forumTopicId: 16806
|
||||
dashedName: convert-celsius-to-fahrenheit
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
L'algoritmo per convertire i gradi da Celsius a Fahrenheit è la temperatura in Celsius moltiplicata per `9/5`, più `32`.
|
||||
|
||||
Ti viene data una variabile `celsius` che rappresenta una temperatura in Celsius. Usa la variabile `fahrenheit` già definita e assegnale la temperatura Fahrenheit equivalente alla temperatura Celsius specificata. Usa l'algoritmo definito sopra per aiutarti a convertire la temperatura da Celsius a Fahrenheit.
|
||||
|
||||
# --hints--
|
||||
|
||||
`convertToF(0)` dovrebbe restituire un numero
|
||||
|
||||
```js
|
||||
assert(typeof convertToF(0) === 'number');
|
||||
```
|
||||
|
||||
`convertToF(-30)` dovrebbe restituire un valore di `-22`
|
||||
|
||||
```js
|
||||
assert(convertToF(-30) === -22);
|
||||
```
|
||||
|
||||
`convertToF(-10)` dovrebbe restituire un valore di `14`
|
||||
|
||||
```js
|
||||
assert(convertToF(-10) === 14);
|
||||
```
|
||||
|
||||
`convertToF(0)` dovrebbe restituire un valore di `32`
|
||||
|
||||
```js
|
||||
assert(convertToF(0) === 32);
|
||||
```
|
||||
|
||||
`convertToF(20)` dovrebbe restituire un valore di `68`
|
||||
|
||||
```js
|
||||
assert(convertToF(20) === 68);
|
||||
```
|
||||
|
||||
`convertToF(30)` dovrebbe restituire un valore di `86`
|
||||
|
||||
```js
|
||||
assert(convertToF(30) === 86);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function convertToF(celsius) {
|
||||
let fahrenheit;
|
||||
return fahrenheit;
|
||||
}
|
||||
|
||||
convertToF(30);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function convertToF(celsius) {
|
||||
let fahrenheit = celsius * 9/5 + 32;
|
||||
|
||||
return fahrenheit;
|
||||
}
|
||||
|
||||
convertToF(30);
|
||||
```
|
@ -0,0 +1,73 @@
|
||||
---
|
||||
id: a302f7aae1aa3152a5b413bc
|
||||
title: Fattoriale di un numero
|
||||
challengeType: 5
|
||||
forumTopicId: 16013
|
||||
dashedName: factorialize-a-number
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Restituisci il fattoriale del numero intero fornito.
|
||||
|
||||
Se l'intero è rappresentato con la lettera `n`, un fattoriale è il prodotto di tutti gli interi positivi minori o uguali a `n`.
|
||||
|
||||
I fattoriali sono spesso rappresentati con la notazione abbreviata `n!`
|
||||
|
||||
Per esempio: `5! = 1 * 2 * 3 * 4 * 5 = 120`
|
||||
|
||||
Verranno passati alla funzione solo interi maggiori o uguali a zero.
|
||||
|
||||
# --hints--
|
||||
|
||||
`factorialize(5)` dovrebbe restituire un numero.
|
||||
|
||||
```js
|
||||
assert(typeof factorialize(5) === 'number');
|
||||
```
|
||||
|
||||
`factorialize(5)` dovrebbe restituire `120`.
|
||||
|
||||
```js
|
||||
assert(factorialize(5) === 120);
|
||||
```
|
||||
|
||||
`factorialize(10)` dovrebbe restituire `3628800`.
|
||||
|
||||
```js
|
||||
assert(factorialize(10) === 3628800);
|
||||
```
|
||||
|
||||
`factorialize(20)` dovrebbe restituire `2432902008176640000`.
|
||||
|
||||
```js
|
||||
assert(factorialize(20) === 2432902008176640000);
|
||||
```
|
||||
|
||||
`factorialize(0)` dovrebbe restituire `1`.
|
||||
|
||||
```js
|
||||
assert(factorialize(0) === 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function factorialize(num) {
|
||||
return num;
|
||||
}
|
||||
|
||||
factorialize(5);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function factorialize(num) {
|
||||
return num < 1 ? 1 : num * factorialize(num - 1);
|
||||
}
|
||||
|
||||
factorialize(5);
|
||||
```
|
@ -0,0 +1,63 @@
|
||||
---
|
||||
id: adf08ec01beb4f99fc7a68f2
|
||||
title: Falsy Bouncer
|
||||
challengeType: 5
|
||||
forumTopicId: 16014
|
||||
dashedName: falsy-bouncer
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Rimuovi tutti i valori falsy da un array.
|
||||
|
||||
I valori falsy in JavaScript sono `false`, `null`, `0`, `""`, `undefined` e `NaN`.
|
||||
|
||||
Suggerimento: Prova a convertire ogni valore in un Booleano.
|
||||
|
||||
# --hints--
|
||||
|
||||
`bouncer([7, "ate", "", false, 9])` dovrebbe restituire `[7, "ate", 9]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer([7, 'ate', '', false, 9]), [7, 'ate', 9]);
|
||||
```
|
||||
|
||||
`bouncer(["a", "b", "c"])` dovrebbe restituire `["a", "b", "c"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer(['a', 'b', 'c']), ['a', 'b', 'c']);
|
||||
```
|
||||
|
||||
`bouncer([false, null, 0, NaN, undefined, ""])` dovrebbe restituire `[]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer([false, null, 0, NaN, undefined, '']), []);
|
||||
```
|
||||
|
||||
`bouncer([null, NaN, 1, 2, undefined])` dovrebbe restituire `[1, 2]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer([null, NaN, 1, 2, undefined]), [1, 2]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function bouncer(arr) {
|
||||
return arr;
|
||||
}
|
||||
|
||||
bouncer([7, "ate", "", false, 9]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function bouncer(arr) {
|
||||
return arr.filter(e => e);
|
||||
}
|
||||
|
||||
bouncer([7, "ate", "", false, 9]);
|
||||
```
|
@ -0,0 +1,87 @@
|
||||
---
|
||||
id: a26cbbe9ad8655a977e1ceb5
|
||||
title: Trovare la parola più lunga in una stringa
|
||||
challengeType: 5
|
||||
forumTopicId: 16015
|
||||
dashedName: find-the-longest-word-in-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Restituisci la lunghezza della parola più lunga nella frase fornita.
|
||||
|
||||
Il tuo risultato dovrebbe essere un numero.
|
||||
|
||||
# --hints--
|
||||
|
||||
`findLongestWordLength("The quick brown fox jumped over the lazy dog")` dovrebbe restituire un numero.
|
||||
|
||||
```js
|
||||
assert(
|
||||
typeof findLongestWordLength(
|
||||
'The quick brown fox jumped over the lazy dog'
|
||||
) === 'number'
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestWordLength("The quick brown fox jumped over the lazy dog")` dovrebbe restituire `6`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
findLongestWordLength('The quick brown fox jumped over the lazy dog') === 6
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestWordLength("May the force be with you")` dovrebbe restituire `5`.
|
||||
|
||||
```js
|
||||
assert(findLongestWordLength('May the force be with you') === 5);
|
||||
```
|
||||
|
||||
`findLongestWordLength("Google do a barrel roll")` dovrebbe restituire `6`.
|
||||
|
||||
```js
|
||||
assert(findLongestWordLength('Google do a barrel roll') === 6);
|
||||
```
|
||||
|
||||
`findLongestWordLength("What is the average airspeed velocity of an unladen swallow")` dovrebbe restituire `8`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
findLongestWordLength(
|
||||
'What is the average airspeed velocity of an unladen swallow'
|
||||
) === 8
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")` dovrebbe restituire `19`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
findLongestWordLength(
|
||||
'What if we try a super-long word such as otorhinolaryngology'
|
||||
) === 19
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function findLongestWordLength(str) {
|
||||
return str.length;
|
||||
}
|
||||
|
||||
findLongestWordLength("The quick brown fox jumped over the lazy dog");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function findLongestWordLength(str) {
|
||||
return str.split(' ').sort((a, b) => b.length - a.length)[0].length;
|
||||
}
|
||||
|
||||
findLongestWordLength("The quick brown fox jumped over the lazy dog");
|
||||
```
|
@ -0,0 +1,58 @@
|
||||
---
|
||||
id: a6e40f1041b06c996f7b2406
|
||||
title: Chi trova tiene
|
||||
challengeType: 5
|
||||
forumTopicId: 16016
|
||||
dashedName: finders-keepers
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Crea una funzione che scorre un array `arr` e restituisce il primo elemento che passa un 'test di verità'. Ciò significa che, dato un elemento `x`, il 'test di verità' viene superato se `func(x)` è `true`. Se nessun elemento supera il test, restituisce `undefined`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })` dovrebbe restituire `8`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
findElement([1, 3, 5, 8, 9, 10], function (num) {
|
||||
return num % 2 === 0;
|
||||
}),
|
||||
8
|
||||
);
|
||||
```
|
||||
|
||||
`findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })` dovrebbe restituire `undefined`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
findElement([1, 3, 5, 9], function (num) {
|
||||
return num % 2 === 0;
|
||||
}),
|
||||
undefined
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function findElement(arr, func) {
|
||||
let num = 0;
|
||||
return num;
|
||||
}
|
||||
|
||||
findElement([1, 2, 3, 4], num => num % 2 === 0);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function findElement(arr, func) {
|
||||
return arr.filter(func)[0];
|
||||
}
|
||||
|
||||
findElement([1, 2, 3, 4], num => num % 2 === 0);
|
||||
```
|
@ -0,0 +1,117 @@
|
||||
---
|
||||
id: af2170cad53daa0770fabdea
|
||||
title: Mutazioni
|
||||
challengeType: 5
|
||||
forumTopicId: 16025
|
||||
dashedName: mutations
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Restituisci `true` se la stringa nel primo elemento dell'array contiene tutte le lettere della stringa nel secondo elemento dell'array.
|
||||
|
||||
Per esempio, `["hello", "Hello"]`, dovrebbe restituire `true` perché tutte le lettere nella seconda stringa sono presenti nel primo, ignorando la maiuscola.
|
||||
|
||||
Gli argomenti `["hello", "hey"]` dovrebbero restituire `false` perché la stringa `hello` non contiene una `y`.
|
||||
|
||||
Infine, `["Alien", "line"]`, dovrebbe restituire `true` perché tutte le lettere in `line` sono presenti in `Alien`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`mutation(["hello", "hey"])` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert(mutation(['hello', 'hey']) === false);
|
||||
```
|
||||
|
||||
`mutation(["hello", "Hello"])` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert(mutation(['hello', 'Hello']) === true);
|
||||
```
|
||||
|
||||
`mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert(mutation(['zyxwvutsrqponmlkjihgfedcba', 'qrstu']) === true);
|
||||
```
|
||||
|
||||
`mutation(["Mary", "Army"])` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert(mutation(['Mary', 'Army']) === true);
|
||||
```
|
||||
|
||||
`mutation(["Mary", "Aarmy"])` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert(mutation(['Mary', 'Aarmy']) === true);
|
||||
```
|
||||
|
||||
`mutation(["Alien", "line"])` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert(mutation(['Alien', 'line']) === true);
|
||||
```
|
||||
|
||||
`mutation(["floor", "for"])` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert(mutation(['floor', 'for']) === true);
|
||||
```
|
||||
|
||||
`mutation(["hello", "neo"])` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert(mutation(['hello', 'neo']) === false);
|
||||
```
|
||||
|
||||
`mutation(["voodoo", "no"])` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert(mutation(['voodoo', 'no']) === false);
|
||||
```
|
||||
|
||||
`mutation(["ate", "date"])` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert(mutation(['ate', 'date']) === false);
|
||||
```
|
||||
|
||||
`mutation(["Tiger", "Zebra"])` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert(mutation(['Tiger', 'Zebra']) === false);
|
||||
```
|
||||
|
||||
`mutation(["Noel", "Ole"])` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert(mutation(['Noel', 'Ole']) === true);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function mutation(arr) {
|
||||
return arr;
|
||||
}
|
||||
|
||||
mutation(["hello", "hey"]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function mutation(arr) {
|
||||
let hash = Object.create(null);
|
||||
|
||||
arr[0].toLowerCase().split('').forEach(c => hash[c] = true);
|
||||
|
||||
return !arr[1].toLowerCase().split('').filter(c => !hash[c]).length;
|
||||
}
|
||||
|
||||
mutation(["hello", "hey"]);
|
||||
```
|
@ -0,0 +1,84 @@
|
||||
---
|
||||
id: afcc8d540bea9ea2669306b6
|
||||
title: Ripetere una stringa Ripeti una stringa
|
||||
challengeType: 5
|
||||
forumTopicId: 16041
|
||||
dashedName: repeat-a-string-repeat-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Ripeti una data stringa `str` (primo argomento) per `num` volte (secondo argomento). Restituisci una stringa vuota se `num` non è un numero positivo. Ai fini di questa sfida, *non* utilizzare il metodo integrato `.repeat()`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`repeatStringNumTimes("*", 3)` dovrebbe restituire la stringa `***`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('*', 3) === '***');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 3)` dovrebbe restituire la stringa `abcabcabc`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 3) === 'abcabcabc');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 4)` dovrebbe restituire la stringa `abcabcabcabc`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 4) === 'abcabcabcabc');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 1)` dovrebbe restituire la stringa `abc`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 1) === 'abc');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("*", 8)` dovrebbe restituire la stringa `********`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('*', 8) === '********');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", -2)` dovrebbe restituire una stringa vuota (`""`).
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', -2) === '');
|
||||
```
|
||||
|
||||
Il metodo integrato `repeat()` non dovrebbe essere usato.
|
||||
|
||||
```js
|
||||
assert(!/\.repeat/g.test(code));
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 0)` dovrebbe restituire `""`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 0) === '');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function repeatStringNumTimes(str, num) {
|
||||
return str;
|
||||
}
|
||||
|
||||
repeatStringNumTimes("abc", 3);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function repeatStringNumTimes(str, num) {
|
||||
if (num < 1) return '';
|
||||
return num === 1 ? str : str + repeatStringNumTimes(str, num-1);
|
||||
}
|
||||
|
||||
repeatStringNumTimes("abc", 3);
|
||||
```
|
@ -0,0 +1,92 @@
|
||||
---
|
||||
id: a789b3483989747d63b0e427
|
||||
title: Restituire i numeri più grandi negli array
|
||||
challengeType: 5
|
||||
forumTopicId: 16042
|
||||
dashedName: return-largest-numbers-in-arrays
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Restituisci un array formato dai numeri più grandi di ciascuno dei sotto-array forniti. Per semplicità, l'array fornito conterrà esattamente 4 sotto-array.
|
||||
|
||||
Ricorda, puoi iterare attraverso un array con un semplice ciclo e accedere a ogni elemento con la sintassi array `arr[i]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])` dovrebbe restituire un array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
largestOfFour([
|
||||
[4, 5, 1, 3],
|
||||
[13, 27, 18, 26],
|
||||
[32, 35, 37, 39],
|
||||
[1000, 1001, 857, 1]
|
||||
]).constructor === Array
|
||||
);
|
||||
```
|
||||
|
||||
`largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])` dovrebbe restituire `[27, 5, 39, 1001]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
largestOfFour([
|
||||
[13, 27, 18, 26],
|
||||
[4, 5, 1, 3],
|
||||
[32, 35, 37, 39],
|
||||
[1000, 1001, 857, 1]
|
||||
]),
|
||||
[27, 5, 39, 1001]
|
||||
);
|
||||
```
|
||||
|
||||
`largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]])` dovrebbe restituire `[9, 35, 97, 1000000]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
largestOfFour([
|
||||
[4, 9, 1, 3],
|
||||
[13, 35, 18, 26],
|
||||
[32, 35, 97, 39],
|
||||
[1000000, 1001, 857, 1]
|
||||
]),
|
||||
[9, 35, 97, 1000000]
|
||||
);
|
||||
```
|
||||
|
||||
`largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])` dovrebbe restituire `[25, 48, 21, -3]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
largestOfFour([
|
||||
[17, 23, 25, 12],
|
||||
[25, 7, 34, 48],
|
||||
[4, -10, 18, 21],
|
||||
[-72, -3, -17, -10]
|
||||
]),
|
||||
[25, 48, 21, -3]
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function largestOfFour(arr) {
|
||||
return arr;
|
||||
}
|
||||
|
||||
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function largestOfFour(arr) {
|
||||
return arr.map(subArr => Math.max.apply(null, subArr));
|
||||
}
|
||||
|
||||
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
|
||||
```
|
@ -0,0 +1,63 @@
|
||||
---
|
||||
id: a202eed8fc186c8434cb6d61
|
||||
title: Invertire una stringa
|
||||
challengeType: 5
|
||||
forumTopicId: 16043
|
||||
dashedName: reverse-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Inverti la stringa fornita.
|
||||
|
||||
Potrebbe essere necessario trasformare la stringa in un array prima di poterla invertire.
|
||||
|
||||
Il tuo risultato deve essere una stringa.
|
||||
|
||||
# --hints--
|
||||
|
||||
`reverseString("hello")` dovrebbe restituire una stringa.
|
||||
|
||||
```js
|
||||
assert(typeof reverseString('hello') === 'string');
|
||||
```
|
||||
|
||||
`reverseString("hello")` dovrebbe restituire la stringa `olleh`.
|
||||
|
||||
```js
|
||||
assert(reverseString('hello') === 'olleh');
|
||||
```
|
||||
|
||||
`reverseString("Howdy")` dovrebbe restituire la stringa `ydwoH`.
|
||||
|
||||
```js
|
||||
assert(reverseString('Howdy') === 'ydwoH');
|
||||
```
|
||||
|
||||
`reverseString("Greetings from Earth")` dovrebbe restituire la stringa `htraE morf sgniteerG`.
|
||||
|
||||
```js
|
||||
assert(reverseString('Greetings from Earth') === 'htraE morf sgniteerG');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function reverseString(str) {
|
||||
return str;
|
||||
}
|
||||
|
||||
reverseString("hello");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function reverseString(str) {
|
||||
return str.split('').reverse().join('');
|
||||
}
|
||||
|
||||
reverseString("hello");
|
||||
```
|
@ -0,0 +1,98 @@
|
||||
---
|
||||
id: 579e2a2c335b9d72dd32e05c
|
||||
title: Taglia e incolla
|
||||
challengeType: 5
|
||||
forumTopicId: 301148
|
||||
dashedName: slice-and-splice
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Ti vengono dati due array e un indice.
|
||||
|
||||
Copia ogni elemento del primo array nel secondo array, in ordine.
|
||||
|
||||
Inizia inserendo gli elementi all'indice `n` del secondo array.
|
||||
|
||||
Restituisci l'array risultante. Gli array di input dovrebbero rimanere gli stessi dopo l'esecuzione della funzione.
|
||||
|
||||
# --hints--
|
||||
|
||||
`frankenSplice([1, 2, 3], [4, 5], 1)` dovrebbe restituire `[4, 1, 2, 3, 5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(frankenSplice([1, 2, 3], [4, 5], 1), [4, 1, 2, 3, 5]);
|
||||
```
|
||||
|
||||
`frankenSplice([1, 2], ["a", "b"], 1)` dovrebbe restituire `["a", 1, 2, "b"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(frankenSplice(testArr1, testArr2, 1), ['a', 1, 2, 'b']);
|
||||
```
|
||||
|
||||
`frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)` dovrebbe restituire `["head", "shoulders", "claw", "tentacle", "knees", "toes"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
frankenSplice(
|
||||
['claw', 'tentacle'],
|
||||
['head', 'shoulders', 'knees', 'toes'],
|
||||
2
|
||||
),
|
||||
['head', 'shoulders', 'claw', 'tentacle', 'knees', 'toes']
|
||||
);
|
||||
```
|
||||
|
||||
Tutti gli elementi del primo array dovrebbero essere aggiunti al secondo array nel loro ordine originale.
|
||||
|
||||
```js
|
||||
assert.deepEqual(frankenSplice([1, 2, 3, 4], [], 0), [1, 2, 3, 4]);
|
||||
```
|
||||
|
||||
Il primo array dovrebbe rimanere lo stesso dopo l'esecuzione della funzione.
|
||||
|
||||
```js
|
||||
frankenSplice(testArr1, testArr2, 1);
|
||||
assert.deepEqual(testArr1, [1, 2]);
|
||||
```
|
||||
|
||||
Il secondo array dovrebbe rimanere lo stesso dopo l'esecuzione della funzione.
|
||||
|
||||
```js
|
||||
frankenSplice(testArr1, testArr2, 1);
|
||||
assert.deepEqual(testArr2, ['a', 'b']);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
let testArr1 = [1, 2];
|
||||
let testArr2 = ["a", "b"];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function frankenSplice(arr1, arr2, n) {
|
||||
return arr2;
|
||||
}
|
||||
|
||||
frankenSplice([1, 2, 3], [4, 5, 6], 1);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function frankenSplice(arr1, arr2, n) {
|
||||
// It's alive. It's alive!
|
||||
let result = arr2.slice();
|
||||
for (let i = 0; i < arr1.length; i++) {
|
||||
result.splice(n+i, 0, arr1[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
frankenSplice([1, 2, 3], [4, 5], 1);
|
||||
```
|
@ -0,0 +1,64 @@
|
||||
---
|
||||
id: ab6137d4e35944e21037b769
|
||||
title: Scrivere in maiuscolo le iniziali di ogni parola
|
||||
challengeType: 5
|
||||
forumTopicId: 16088
|
||||
dashedName: title-case-a-sentence
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Restituisci la stringa fornita con la prima lettera di ogni parola in maiuscolo. Assicurati che il resto della parola sia in minuscolo.
|
||||
|
||||
Ai fini di questo esercizio, dovresti anche mettere in maiuscolo le parole di collegamento come `the` e `of`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`titleCase("I'm a little tea pot")` dovrebbe restituire una stringa.
|
||||
|
||||
```js
|
||||
assert(typeof titleCase("I'm a little tea pot") === 'string');
|
||||
```
|
||||
|
||||
`titleCase("I'm a little tea pot")` dovrebbe restituire la stringa `I'm A Little Tea Pot`.
|
||||
|
||||
```js
|
||||
assert(titleCase("I'm a little tea pot") === "I'm A Little Tea Pot");
|
||||
```
|
||||
|
||||
`titleCase("sHoRt AnD sToUt")` dovrebbe restituire la stringa `Short And Stout`.
|
||||
|
||||
```js
|
||||
assert(titleCase('sHoRt AnD sToUt') === 'Short And Stout');
|
||||
```
|
||||
|
||||
`titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")` dovrebbe restituire la stringa `Here Is My Handle Here Is My Spout`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
titleCase('HERE IS MY HANDLE HERE IS MY SPOUT') ===
|
||||
'Here Is My Handle Here Is My Spout'
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function titleCase(str) {
|
||||
return str;
|
||||
}
|
||||
|
||||
titleCase("I'm a little tea pot");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function titleCase(str) {
|
||||
return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.substring(1).toLowerCase()).join(' ');
|
||||
}
|
||||
|
||||
titleCase("I'm a little tea pot");
|
||||
```
|
@ -0,0 +1,91 @@
|
||||
---
|
||||
id: ac6993d51946422351508a41
|
||||
title: Troncare una stringa
|
||||
challengeType: 5
|
||||
forumTopicId: 16089
|
||||
dashedName: truncate-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Tronca una stringa (primo argomento) se è più lunga della massima lunghezza specificata (secondo argomento). Restituisci la stringa troncata con alla fine `...`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", 8)` dovrebbe restituire la stringa `A-tisket...`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
truncateString('A-tisket a-tasket A green and yellow basket', 8) ===
|
||||
'A-tisket...'
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("Peter Piper picked a peck of pickled peppers", 11)` dovrebbe restituire la stringa `Peter Piper...`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
truncateString('Peter Piper picked a peck of pickled peppers', 11) ===
|
||||
'Peter Piper...'
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)` dovrebbe restituire la stringa `A-tisket a-tasket A green and yellow basket`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
truncateString(
|
||||
'A-tisket a-tasket A green and yellow basket',
|
||||
'A-tisket a-tasket A green and yellow basket'.length
|
||||
) === 'A-tisket a-tasket A green and yellow basket'
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)` dovrebbe restituire la stringa `A-tisket a-tasket A green and yellow basket`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
truncateString(
|
||||
'A-tisket a-tasket A green and yellow basket',
|
||||
'A-tisket a-tasket A green and yellow basket'.length + 2
|
||||
) === 'A-tisket a-tasket A green and yellow basket'
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("A-", 1)` dovrebbe restituire la stringa `A...`.
|
||||
|
||||
```js
|
||||
assert(truncateString('A-', 1) === 'A...');
|
||||
```
|
||||
|
||||
`truncateString("Absolutely Longer", 2)` dovrebbe restituire la stringa `Ab...`.
|
||||
|
||||
```js
|
||||
assert(truncateString('Absolutely Longer', 2) === 'Ab...');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function truncateString(str, num) {
|
||||
return str;
|
||||
}
|
||||
|
||||
truncateString("A-tisket a-tasket A green and yellow basket", 8);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function truncateString(str, num) {
|
||||
if (num >= str.length) {
|
||||
return str;
|
||||
}
|
||||
|
||||
return str.slice(0, num) + '...';
|
||||
}
|
||||
|
||||
truncateString("A-tisket a-tasket A green and yellow basket", 8);
|
||||
```
|
@ -0,0 +1,143 @@
|
||||
---
|
||||
id: a24c1a4622e3c05097f71d67
|
||||
title: Qual è il mio posto
|
||||
challengeType: 5
|
||||
forumTopicId: 16094
|
||||
dashedName: where-do-i-belong
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Restituisci l'indice più basso al quale un valore (secondo argomento) deve essere inserito in un array (primo argomento) una volta che è stato ordinato. Il valore restituito dovrebbe essere un numero.
|
||||
|
||||
Per esempio, `getIndexToIns([1,2,3,4], 1.5)` dovrebbe restituire `1` perché è maggiore di `1` (indice 0), ma minore di `2` (indice 1).
|
||||
|
||||
Allo stesso modo, `getIndexToIns([20,3,5], 19)` dovrebbe restituire `2` perché l'array ordinato sarà `[3,5,20]` e `19` è minore di `20` (indice 2) e maggiore di `5` (indice 1).
|
||||
|
||||
# --hints--
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 35)` dovrebbe restituire `3`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([10, 20, 30, 40, 50], 35) === 3);
|
||||
```
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 35)` dovrebbe restituire un numero.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([10, 20, 30, 40, 50], 35) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 30)` dovrebbe restituire `2`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([10, 20, 30, 40, 50], 30) === 2);
|
||||
```
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 30)` dovrebbe restituire un numero.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([10, 20, 30, 40, 50], 30) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([40, 60], 50)` dovrebbe restituire `1`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([40, 60], 50) === 1);
|
||||
```
|
||||
|
||||
`getIndexToIns([40, 60], 50)` dovrebbe restituire un numero.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([40, 60], 50) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([3, 10, 5], 3)` dovrebbe restituire `0`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([3, 10, 5], 3) === 0);
|
||||
```
|
||||
|
||||
`getIndexToIns([3, 10, 5], 3)` dovrebbe restituire un numero.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([3, 10, 5], 3) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([5, 3, 20, 3], 5)` dovrebbe restituire `2`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([5, 3, 20, 3], 5) === 2);
|
||||
```
|
||||
|
||||
`getIndexToIns([5, 3, 20, 3], 5)` dovrebbe restituire un numero.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([5, 3, 20, 3], 5) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 20, 10], 19)` dovrebbe restituire `2`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([2, 20, 10], 19) === 2);
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 20, 10], 19)` dovrebbe restituire un numero.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([2, 20, 10], 19) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 5, 10], 15)` dovrebbe restituire `3`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([2, 5, 10], 15) === 3);
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 5, 10], 15)` dovrebbe restituire un numero.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([2, 5, 10], 15) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([], 1)` dovrebbe restituire `0`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([], 1) === 0);
|
||||
```
|
||||
|
||||
`getIndexToIns([], 1)` dovrebbe restituire un numero.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([], 1) === 'number');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getIndexToIns(arr, num) {
|
||||
return num;
|
||||
}
|
||||
|
||||
getIndexToIns([40, 60], 50);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getIndexToIns(arr, num) {
|
||||
arr = arr.sort((a, b) => a - b);
|
||||
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
if (arr[i] >= num) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return arr.length;
|
||||
}
|
||||
|
||||
getIndexToIns([40, 60], 50);
|
||||
```
|
@ -0,0 +1,82 @@
|
||||
---
|
||||
id: 5a661e0f1068aca922b3ef17
|
||||
title: Accedere ai contenuti dell'array usando la notazione a parentesi
|
||||
challengeType: 1
|
||||
forumTopicId: 301149
|
||||
dashedName: access-an-arrays-contents-using-bracket-notation
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
La caratteristica fondamentale di qualsiasi struttura di dati è, ovviamente, la capacità non solo di memorizzare i dati, ma di essere in grado di recuperare tali dati a comando. Quindi, adesso che abbiamo imparato a creare un array, cominciamo a pensare come possiamo accedere alle informazioni di quell'array.
|
||||
|
||||
Se definiamo un semplice array come il seguente, ci sono 3 elementi:
|
||||
|
||||
```js
|
||||
let ourArray = ["a", "b", "c"];
|
||||
```
|
||||
|
||||
In un array, ogni elemento ha un <dfn>indice</dfn>. Questo indice indica la posizione di quell'elemento nell'array e come lo puoi consultare. Tuttavia è importante notare che gli array JavaScript sono <dfn>indicizzati a zero</dfn>, cioè che il primo elemento di un array è in realtà alla ***zeresima*** posizione, non alla prima. Per recuperare un elemento da un array possiamo racchiudere un indice tra parentesi e aggiungerlo alla fine di un array, o più comunemente, a una variabile che fa riferimento ad un array. Questa notazione si chiama <dfn>notazione a parentesi</dfn>. Ad esempio, se vogliamo recuperare `a` da `ourArray` e assegnarlo a una variabile, possiamo farlo con il seguente codice:
|
||||
|
||||
```js
|
||||
let ourVariable = ourArray[0];
|
||||
```
|
||||
|
||||
Ora `ourVariable` ha il valore di `a`.
|
||||
|
||||
Oltre ad accedere al valore associato ad un indice, è anche possibile *impostare* un indice ad un valore utilizzando la stessa notazione:
|
||||
|
||||
```js
|
||||
ourArray[1] = "not b anymore";
|
||||
```
|
||||
|
||||
Usando la notazione tra parentesi, abbiamo resettato l'elemento all'indice 1 dalla stringa `b`, alla stringa `not b anymore`. Ora `ourArray` è `["a", "not b anymore", "c"]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Per completare questa sfida, imposta la seconda posizione (indice `1`) di `myArray` a quello che vuoi, tranne che alla lettera `b`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray[0]` dovrebbe essere uguale alla lettera `a`
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[0], 'a');
|
||||
```
|
||||
|
||||
`myArray[1]` non deve essere uguale alla lettera `b`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(myArray[1], 'b');
|
||||
```
|
||||
|
||||
`myArray[2]` deve essere uguale alla lettera `c`
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[2], 'c');
|
||||
```
|
||||
|
||||
`myArray[3]` deve essere uguale alla lettera `d`
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[3], 'd');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let myArray = ["a", "b", "c", "d"];
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
console.log(myArray);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let myArray = ["a", "b", "c", "d"];
|
||||
myArray[1] = "e";
|
||||
```
|
@ -0,0 +1,101 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b1a
|
||||
title: Accedere ai nomi delle proprietà con la notazione a parentesi
|
||||
challengeType: 1
|
||||
forumTopicId: 301150
|
||||
dashedName: access-property-names-with-bracket-notation
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Nella prima sfida sugli oggetti abbiamo menzionato l'uso della notazione a parentesi come modo per accedere ai valori delle proprietà utilizzando la valutazione di una variabile. Per esempio, immagina che il nostro oggetto `foods` venga utilizzato in un programma per il registratore di cassa di un supermercato. Abbiamo una funzione che imposta `selectedFood` e vogliamo controllare se nel nostro oggetto `foods` è presente quel cibo. Questo potrebbe apparire così:
|
||||
|
||||
```js
|
||||
let selectedFood = getCurrentFood(scannedItem);
|
||||
let inventory = foods[selectedFood];
|
||||
```
|
||||
|
||||
Questo codice valuterà il valore memorizzato nella variabile `selectedFood` e restituirà il valore di quella proprietà nell'oggetto `foods`, oppure `undefined` se non è presente. La notazione a parentesi è molto utile perché a volte le proprietà dell'oggetto non sono note prima dell'esecuzione o abbiamo bisogno di accedervi in modo più dinamico.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Abbiamo definito una funzione, `checkInventory`, che riceve un elemento scansionato come argomento. Restituisci il valore corrente della proprietà `scannedItem` nell'oggetto `foods`. Puoi supporre che saranno fornite come argomento solo chiavi valide per `checkInventory`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`checkInventory` dovrebbe essere una funzione.
|
||||
|
||||
```js
|
||||
assert.strictEqual(typeof checkInventory, 'function');
|
||||
```
|
||||
|
||||
L'oggetto `foods` dovrebbe avere solo le seguenti coppie di proprietà-valori: `apples: 25`, `oranges: 32`, `plums: 28`, `bananas: 13`, `grapes: 35`, `strawberries: 27`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(foods, {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28,
|
||||
bananas: 13,
|
||||
grapes: 35,
|
||||
strawberries: 27
|
||||
});
|
||||
```
|
||||
|
||||
`checkInventory("apples")` dovrebbe restituire `25`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(checkInventory('apples'), 25);
|
||||
```
|
||||
|
||||
`checkInventory("bananas")` dovrebbe restituire `13`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(checkInventory('bananas'), 13);
|
||||
```
|
||||
|
||||
`checkInventory("strawberries")` dovrebbe restituire `27`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(checkInventory('strawberries'), 27);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let foods = {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28,
|
||||
bananas: 13,
|
||||
grapes: 35,
|
||||
strawberries: 27
|
||||
};
|
||||
|
||||
function checkInventory(scannedItem) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
console.log(checkInventory("apples"));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let foods = {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28,
|
||||
bananas: 13,
|
||||
grapes: 35,
|
||||
strawberries: 27
|
||||
};
|
||||
|
||||
function checkInventory(scannedItem) {
|
||||
return foods[scannedItem];
|
||||
}
|
||||
```
|
@ -0,0 +1,87 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b0e
|
||||
title: Aggiungere elementi ad un array con push() e unshift()
|
||||
challengeType: 1
|
||||
forumTopicId: 301151
|
||||
dashedName: add-items-to-an-array-with-push-and-unshift
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
La lunghezza di un array, così come i tipi di dati che può contenere, non è fissata. Gli array possono essere definiti con un numero qualsiasi di elementi, e gli elementi possono essere aggiunti o rimossi nel tempo; in altre parole, gli array sono <dfn>mutabili</dfn>. In questa sfida, esamineremo due metodi con cui possiamo modificare programmaticamente un array: `Array.push()` e `Array.unshift()`.
|
||||
|
||||
Entrambi i metodi prendono uno o più elementi come parametri e aggiungono questi elementi all'array su cui il metodo è stato chiamato; il metodo `push()` aggiunge elementi alla fine di un array, e `unshift()` aggiunge elementi all'inizio. Considera quanto segue:
|
||||
|
||||
```js
|
||||
let twentyThree = 'XXIII';
|
||||
let romanNumerals = ['XXI', 'XXII'];
|
||||
|
||||
romanNumerals.unshift('XIX', 'XX');
|
||||
```
|
||||
|
||||
`romanNumerals` avrà i valori `['XIX', 'XX', 'XXI', 'XXII']`.
|
||||
|
||||
```js
|
||||
romanNumerals.push(twentyThree);
|
||||
```
|
||||
|
||||
`romanNumerals` avrà i valori `['XIX', 'XX', 'XXI', 'XXII', 'XXIII']`. Nota che possiamo anche passare variabili, il che ci permette una flessibilità ancora maggiore nel modificare dinamicamente i dati del nostro array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Abbiamo definito una funzione, `mixedNumbers`, a cui stiamo passando un array come argomento. Modifica la funzione usando `push()` e `unshift()` per aggiungere `'I', 2, 'three'` all'inizio dell'array e `7, 'VIII', 9` alla fine, in modo che l'array restituito contenga le rappresentazioni dei numeri da 1 a 9 in ordine.
|
||||
|
||||
# --hints--
|
||||
|
||||
`mixedNumbers(["IV", 5, "six"])` adesso dovrebbe restituire `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [
|
||||
'I',
|
||||
2,
|
||||
'three',
|
||||
'IV',
|
||||
5,
|
||||
'six',
|
||||
7,
|
||||
'VIII',
|
||||
9
|
||||
]);
|
||||
```
|
||||
|
||||
La funzione `mixedNumbers` dovrebbe utilizzare il metodo `push()`
|
||||
|
||||
```js
|
||||
assert(mixedNumbers.toString().match(/\.push/));
|
||||
```
|
||||
|
||||
La funzione `mixedNumbers` dovrebbe utilizzare il metodo `unshift()`
|
||||
|
||||
```js
|
||||
assert(mixedNumbers.toString().match(/\.unshift/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function mixedNumbers(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
return arr;
|
||||
}
|
||||
|
||||
console.log(mixedNumbers(['IV', 5, 'six']));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function mixedNumbers(arr) {
|
||||
arr.push(7,'VIII',9);
|
||||
arr.unshift('I',2,'three');
|
||||
return arr;
|
||||
}
|
||||
```
|
@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 587d78b3367417b2b2512b11
|
||||
title: Aggiungere elementi usando splice()
|
||||
challengeType: 1
|
||||
forumTopicId: 301152
|
||||
dashedName: add-items-using-splice
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Ricordi che nell'ultima sfida abbiamo detto che `splice()` può richiedere fino a tre parametri? Bene, è possibile utilizzare il terzo parametro, composto da uno o più elementi, per aggiungerli all'array. Questo può essere incredibilmente utile per scambiare rapidamente un elemento, o un insieme di elementi, con un altro.
|
||||
|
||||
```js
|
||||
const numbers = [10, 11, 12, 12, 15];
|
||||
const startIndex = 3;
|
||||
const amountToDelete = 1;
|
||||
|
||||
numbers.splice(startIndex, amountToDelete, 13, 14);
|
||||
console.log(numbers);
|
||||
```
|
||||
|
||||
La seconda occorrenza di `12` viene rimossa, e aggiungiamo `13` e `14` allo stesso indice. L'array `numbers` ora è `[ 10, 11, 12, 13, 14, 15 ]`.
|
||||
|
||||
Qui iniziamo con una serie di numeri. Poi, passiamo i seguenti dati a `splice()`: L'indice a cui iniziare a eliminare gli elementi (3), il numero di elementi da eliminare (1) e i restanti argomenti (13, 14) saranno inseriti a partire dallo stesso indice. Nota che ci può essere un numero qualsiasi di elementi (separati da virgole) dopo `amountToDelete`, ognuno dei quali verrà inserito.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Abbiamo definito una funzione, `htmlColorNames`, che prende un array di colori HTML come argomento. Modifica la funzione usando `splice()` per rimuovere i primi due elementi dell'array e aggiungere `'DarkSalmon'` e `'BlanchedAlmond'` nei rispettivi posti.
|
||||
|
||||
# --hints--
|
||||
|
||||
`htmlColorNames` dovrebbe restituire `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurquoise", "FireBrick"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
htmlColorNames([
|
||||
'DarkGoldenRod',
|
||||
'WhiteSmoke',
|
||||
'LavenderBlush',
|
||||
'PaleTurquoise',
|
||||
'FireBrick'
|
||||
]),
|
||||
[
|
||||
'DarkSalmon',
|
||||
'BlanchedAlmond',
|
||||
'LavenderBlush',
|
||||
'PaleTurquoise',
|
||||
'FireBrick'
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
La funzione `htmlColorNames` dovrebbe utilizzare il metodo `splice()`
|
||||
|
||||
```js
|
||||
assert(/.splice/.test(code));
|
||||
```
|
||||
|
||||
Non dovresti usare `shift()` o `unshift()`.
|
||||
|
||||
```js
|
||||
assert(!/shift|unshift/.test(code));
|
||||
```
|
||||
|
||||
Non dovresti utilizzare la notazione a parentesi.
|
||||
|
||||
```js
|
||||
assert(!/\[\d\]\s*=/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function htmlColorNames(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
return arr;
|
||||
}
|
||||
|
||||
console.log(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurquoise', 'FireBrick']));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function htmlColorNames(arr) {
|
||||
arr.splice(0,2,'DarkSalmon', 'BlanchedAlmond');
|
||||
return arr;
|
||||
}
|
||||
```
|
@ -0,0 +1,124 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b18
|
||||
title: Aggiungere coppie chiave-valore agli oggetti JavaScript
|
||||
challengeType: 1
|
||||
forumTopicId: 301153
|
||||
dashedName: add-key-value-pairs-to-javascript-objects
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In linea di massima, gli oggetti sono solo collezioni di coppie <dfn>chiave-valore</dfn>. In altre parole, sono dati (<dfn>valori</dfn>) mappati da identificatori univoci chiamati <dfn>proprietà</dfn> (<dfn>chiavi</dfn>). Dai un'occhiata ad un esempio:
|
||||
|
||||
```js
|
||||
const tekkenCharacter = {
|
||||
player: 'Hwoarang',
|
||||
fightingStyle: 'Tae Kwon Doe',
|
||||
human: true
|
||||
};
|
||||
```
|
||||
|
||||
Il codice qui sopra definisce l'oggetto di un personaggio del videogioco Tekken, chiamato `tekkenCharacter`. Ha tre proprietà, ad ognuna delle quali corrisponde un valore specifico. Se desiderassi aggiungere una nuova proprietà, ad esempio "origin", potresti farlo assegnando `origin` all'oggetto:
|
||||
|
||||
```js
|
||||
tekkenCharacter.origin = 'South Korea';
|
||||
```
|
||||
|
||||
Questo usa la notazione a punti. Se tu osservi l'oggetto `tekkenCharacter`, esso ora includerà la proprietà `origin`. Hwoarang aveva anche dei caratteristici capelli arancioni. È possibile aggiungere questa proprietà con la notazione a parentesi scrivendo:
|
||||
|
||||
```js
|
||||
tekkenCharacter['hair color'] = 'dyed orange';
|
||||
```
|
||||
|
||||
La notazione a parentesi è obbligatoria se la proprietà ha uno spazio o se si vuole utilizzare una variabile per selezionare la proprietà. Nel caso precedente, la proprietà è racchiusa tra virgolette per indicarla come una stringa e verrà aggiunta esattamente come mostrato. Senza virgolette, sarà valutata come una variabile e il nome della proprietà sarà qualsiasi valore sia assegnato alla variabile. Ecco un esempio con una variabile:
|
||||
|
||||
```js
|
||||
const eyes = 'eye color';
|
||||
|
||||
tekkenCharacter[eyes] = 'brown';
|
||||
```
|
||||
|
||||
Dopo aver aggiunto tutti gli esempi, l'oggetto apparirà così:
|
||||
|
||||
```js
|
||||
{
|
||||
player: 'Hwoarang',
|
||||
fightingStyle: 'Tae Kwon Doe',
|
||||
human: true,
|
||||
origin: 'South Korea',
|
||||
'hair color': 'dyed orange',
|
||||
'eye color': 'brown'
|
||||
};
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
È stato creato un oggetto `foods` con tre voci. Usando una sintassi a tua scelta, aggiungi altre tre voci ad esso: `bananas` con un valore di `13`, `grapes` con un valore di `35`, e `strawberries` con un valore di `27`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`foods` dovrebbe essere un oggetto.
|
||||
|
||||
```js
|
||||
assert(typeof foods === 'object');
|
||||
```
|
||||
|
||||
L'oggetto `foods` dovrebbe avere una chiave `bananas` con un valore di `13`.
|
||||
|
||||
```js
|
||||
assert(foods.bananas === 13);
|
||||
```
|
||||
|
||||
L'oggetto `foods` dovrebbe avere una chiave `grapes` con un valore di `35`.
|
||||
|
||||
```js
|
||||
assert(foods.grapes === 35);
|
||||
```
|
||||
|
||||
L'oggetto `foods` dovrebbe avere una chiave `strawberries` con un valore di `27`.
|
||||
|
||||
```js
|
||||
assert(foods.strawberries === 27);
|
||||
```
|
||||
|
||||
Le coppie chiave-valore devono essere impostate usando la notazione punto o parentesi.
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.search(/bananas:/) === -1 &&
|
||||
code.search(/grapes:/) === -1 &&
|
||||
code.search(/strawberries:/) === -1
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let foods = {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
console.log(foods);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let foods = {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28
|
||||
};
|
||||
|
||||
foods['bananas'] = 13;
|
||||
foods['grapes'] = 35;
|
||||
foods['strawberries'] = 27;
|
||||
```
|
@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b14
|
||||
title: Verificare la presenza di un elemento con indexOf()
|
||||
challengeType: 1
|
||||
forumTopicId: 301154
|
||||
dashedName: check-for-the-presence-of-an-element-with-indexof
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Dal momento che gli array possono essere cambiati, o *mutati*, in qualsiasi momento, non c'è alcuna garanzia su dove sia un particolare dato in un determinato array, o se quell'elemento esista ancora. Fortunatamente, JavaScript ci fornisce un altro metodo nativo, `indexOf()`, che ci permette di controllare rapidamente e facilmente la presenza di un elemento in un array. `indexOf()` prende un elemento come parametro, e quando chiamato, restituisce la posizione, o indice, di quell'elemento, o `-1` se l'elemento non è presente nell'array.
|
||||
|
||||
Ad esempio:
|
||||
|
||||
```js
|
||||
let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];
|
||||
|
||||
fruits.indexOf('dates');
|
||||
fruits.indexOf('oranges');
|
||||
fruits.indexOf('pears');
|
||||
```
|
||||
|
||||
`indexOf('dates')` restituisce `-1`, `indexOf('oranges')` restituisce `2`e `indexOf('pears')` restituisce `1` (il primo indice in cui è presente il rispettivo elemento).
|
||||
|
||||
# --instructions--
|
||||
|
||||
`indexOf()` può essere incredibilmente utile per verificare rapidamente la presenza di un elemento in un array. Abbiamo definito una funzione, `quickCheck`, che richiede un array e un elemento come argomenti. Modifica la funzione usando `indexOf()` in modo che restituisca `true` se l'elemento passato è nell'array, e `false` se non lo è.
|
||||
|
||||
# --hints--
|
||||
|
||||
La funzione `quickCheck` dovrebbe restituire un booleano (`true` o `false`), non una stringa (`"true"` o `"false"`)
|
||||
|
||||
```js
|
||||
assert.isBoolean(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
|
||||
```
|
||||
|
||||
`quickCheck(["squash", "onions", "shallots"], "mushrooms")` dovrebbe restituire `false`
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'),
|
||||
false
|
||||
);
|
||||
```
|
||||
|
||||
`quickCheck(["onions", "squash", "shallots"], "onions")` dovrebbe restituire `true`
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
quickCheck(['onions', 'squash', 'shallots'], 'onions'),
|
||||
true
|
||||
);
|
||||
```
|
||||
|
||||
`quickCheck([3, 5, 9, 125, 45, 2], 125)` dovrebbe restituire `true`
|
||||
|
||||
```js
|
||||
assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true);
|
||||
```
|
||||
|
||||
`quickCheck([true, false, false], undefined)` dovrebbe restituire `false`
|
||||
|
||||
```js
|
||||
assert.strictEqual(quickCheck([true, false, false], undefined), false);
|
||||
```
|
||||
|
||||
La funzione `quickCheck` dovrebbe utilizzare il metodo `indexOf()`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function quickCheck(arr, elem) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function quickCheck(arr, elem) {
|
||||
return arr.indexOf(elem) >= 0;
|
||||
}
|
||||
```
|
@ -0,0 +1,161 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1c
|
||||
title: Verificare se un oggetto ha una proprietà
|
||||
challengeType: 1
|
||||
forumTopicId: 301155
|
||||
dashedName: check-if-an-object-has-a-property
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Adesso possiamo aggiungere, modificare e rimuovere chiavi dagli oggetti. Ma se volessimo solo sapere se un oggetto ha una determinata proprietà? JavaScript ci fornisce due modi diversi per farlo. Uno utilizza il metodo `hasOwnProperty()` e l'altro usa la parola chiave `in`. Se abbiamo un oggetto `users` con una proprietà `Alan`, potremmo verificare la sua presenza in uno dei seguenti modi:
|
||||
|
||||
```js
|
||||
users.hasOwnProperty('Alan');
|
||||
'Alan' in users;
|
||||
```
|
||||
|
||||
Entrambi restituirebbero `true`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Finisci di scrivere la funzione in modo che restituisca true se l'oggetto ad essa passato contiene tutti e quattro i nomi, `Alan`, `Jeff`, `Sarah` e `Ryan`, e false altrimenti.
|
||||
|
||||
# --hints--
|
||||
|
||||
Non dovresti accedere direttamente all'oggetto `users`
|
||||
|
||||
```js
|
||||
|
||||
assert(code.match(/users/gm).length <= 2)
|
||||
|
||||
```
|
||||
|
||||
L'oggetto `users` dovrebbe contenere solo le chiavi `Alan`, `Jeff`, `Sarah`e `Ryan`
|
||||
|
||||
```js
|
||||
assert(
|
||||
'Alan' in users &&
|
||||
'Jeff' in users &&
|
||||
'Sarah' in users &&
|
||||
'Ryan' in users &&
|
||||
Object.keys(users).length === 4
|
||||
);
|
||||
```
|
||||
|
||||
La funzione `isEveryoneHere` dovrebbe restituire `true` se `Alan`, `Jeff`, `Sarah` e `Ryan` sono proprietà dell'oggetto ad essa passato.
|
||||
|
||||
```js
|
||||
assert(isEveryoneHere(users) === true);
|
||||
```
|
||||
|
||||
La funzione `isEveryoneHere` dovrebbe restituire `false` se `Alan` non è una proprietà dell'oggetto ad essa passato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
delete users.Alan;
|
||||
return isEveryoneHere(users);
|
||||
})() === false
|
||||
);
|
||||
```
|
||||
|
||||
La funzione `isEveryoneHere` dovrebbe restituire `false` se `Jeff` non è una proprietà dell'oggetto ad essa passato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
delete users.Jeff;
|
||||
return isEveryoneHere(users);
|
||||
})() === false
|
||||
);
|
||||
```
|
||||
|
||||
La funzione `isEveryoneHere` dovrebbe restituire `false` se `Sarah` non è una proprietà dell'oggetto ad essa passato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
delete users.Sarah;
|
||||
return isEveryoneHere(users);
|
||||
})() === false
|
||||
);
|
||||
```
|
||||
|
||||
La funzione `isEveryoneHere` dovrebbe restituire `false` se `Ryan` non è una proprietà dell'oggetto ad essa passato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
delete users.Ryan;
|
||||
return isEveryoneHere(users);
|
||||
})() === false
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let users = {
|
||||
Alan: {
|
||||
age: 27,
|
||||
online: true
|
||||
},
|
||||
Jeff: {
|
||||
age: 32,
|
||||
online: true
|
||||
},
|
||||
Sarah: {
|
||||
age: 48,
|
||||
online: true
|
||||
},
|
||||
Ryan: {
|
||||
age: 19,
|
||||
online: true
|
||||
}
|
||||
};
|
||||
|
||||
function isEveryoneHere(userObj) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
console.log(isEveryoneHere(users));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let users = {
|
||||
Alan: {
|
||||
age: 27,
|
||||
online: true
|
||||
},
|
||||
Jeff: {
|
||||
age: 32,
|
||||
online: true
|
||||
},
|
||||
Sarah: {
|
||||
age: 48,
|
||||
online: true
|
||||
},
|
||||
Ryan: {
|
||||
age: 19,
|
||||
online: true
|
||||
}
|
||||
};
|
||||
|
||||
function isEveryoneHere(userObj) {
|
||||
return [
|
||||
'Alan',
|
||||
'Jeff',
|
||||
'Sarah',
|
||||
'Ryan'
|
||||
].every(user => userObj.hasOwnProperty(user));
|
||||
}
|
||||
|
||||
console.log(isEveryoneHere(users));
|
||||
```
|
@ -0,0 +1,63 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b17
|
||||
title: Combinare gli array con l'operatore di espansione
|
||||
challengeType: 1
|
||||
forumTopicId: 301156
|
||||
dashedName: combine-arrays-with-the-spread-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Un altro enorme vantaggio dell'operatore di <dfn>espansione</dfn> è la capacità di combinare array, o di inserire tutti gli elementi di un array in un altro, a partire da qualsiasi indice. Con le sintassi più tradizionali, possiamo concatenare array, ma questo ci permette solo di unire array alla fine di uno, e all'inizio di un altro. La sintassi a espansione rende estremamente semplice la seguente operazione:
|
||||
|
||||
```js
|
||||
let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];
|
||||
|
||||
let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];
|
||||
```
|
||||
|
||||
`thatArray` avrà i valori `['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']`.
|
||||
|
||||
Utilizzando la sintassi a espansione, abbiamo appena realizzato un'operazione che sarebbe stata più complessa e più prolissa se avessimo usato metodi tradizionali.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Abbiamo definito una funzione `spreadOut` che restituisce la variabile `sentence`. Modifica la funzione usando l'operatore <dfn>di espansione</dfn> in modo che restituisca l'array `['learning', 'to', 'code', 'is', 'fun']`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`spreadOut` dovrebbe restituire `["learning", "to", "code", "is", "fun"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(spreadOut(), ['learning', 'to', 'code', 'is', 'fun']);
|
||||
```
|
||||
|
||||
La funzione `spreadOut` dovrebbe utilizzare la sintassi a espansione
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function spreadOut() {
|
||||
let fragment = ['to', 'code'];
|
||||
let sentence; // Change this line
|
||||
return sentence;
|
||||
}
|
||||
|
||||
console.log(spreadOut());
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function spreadOut() {
|
||||
let fragment = ['to', 'code'];
|
||||
let sentence = ['learning', ...fragment, 'is', 'fun'];
|
||||
return sentence;
|
||||
}
|
||||
```
|
@ -0,0 +1,102 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b13
|
||||
title: Copiare un array con l'operatore di espansione
|
||||
challengeType: 1
|
||||
forumTopicId: 301157
|
||||
dashedName: copy-an-array-with-the-spread-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Mentre `slice()` ci permette di essere selettivi su quali elementi di un array copiare, tra diverse altre attività utili, il nuovo <dfn>operatore di espansione</dfn> di ES6 ci permette di copiare facilmente *tutti* gli elementi di un array, in ordine, con una sintassi semplice e molto leggibile. La sintassi a espansione è semplicemente questa: `...`
|
||||
|
||||
In pratica, possiamo usare l'operatore di espansione per copiare un array in questo modo:
|
||||
|
||||
```js
|
||||
let thisArray = [true, true, undefined, false, null];
|
||||
let thatArray = [...thisArray];
|
||||
```
|
||||
|
||||
`thatArray` è uguale a `[true, true, undefined, false, null]`. `thisArray` rimane invariato e `thatArray` contiene gli stessi elementi di `thisArray`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Abbiamo definito una funzione, `copyMachine` che prende `arr` (un array) e `num` (un numero) come argomenti. La funzione dovrebbe restituire un nuovo array composto da `num` copie di `arr`. Abbiamo fatto la maggior parte del lavoro per te, ma non funziona ancora abbastanza bene. Modifica la funzione utilizzando la sintassi di espansione in modo che funzioni correttamente (suggerimento: un altro metodo che abbiamo già trattato potrebbe essere utile qui!).
|
||||
|
||||
# --hints--
|
||||
|
||||
`copyMachine([true, false, true], 2)` dovrebbe restituire `[[true, false, true], [true, false, true]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([true, false, true], 2), [
|
||||
[true, false, true],
|
||||
[true, false, true]
|
||||
]);
|
||||
```
|
||||
|
||||
`copyMachine([1, 2, 3], 5)` dovrebbe restituire `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([1, 2, 3], 5), [
|
||||
[1, 2, 3],
|
||||
[1, 2, 3],
|
||||
[1, 2, 3],
|
||||
[1, 2, 3],
|
||||
[1, 2, 3]
|
||||
]);
|
||||
```
|
||||
|
||||
`copyMachine([true, true, null], 1)` dovrebbe restituire `[[true, true, null]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]]);
|
||||
```
|
||||
|
||||
`copyMachine(["it works"], 3)` dovrebbe restituire `[["it works"], ["it works"], ["it works"]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine(['it works'], 3), [
|
||||
['it works'],
|
||||
['it works'],
|
||||
['it works']
|
||||
]);
|
||||
```
|
||||
|
||||
La funzione `copyMachine` dovrebbe utilizzare lo `spread operator` (operatore di espansione) con l'array `arr`
|
||||
|
||||
```js
|
||||
assert(code.match(/\.\.\.arr/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function copyMachine(arr, num) {
|
||||
let newArr = [];
|
||||
while (num >= 1) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
num--;
|
||||
}
|
||||
return newArr;
|
||||
}
|
||||
|
||||
console.log(copyMachine([true, false, true], 2));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function copyMachine(arr,num){
|
||||
let newArr=[];
|
||||
while(num >=1){
|
||||
newArr.push([...arr]);
|
||||
num--;
|
||||
}
|
||||
return newArr;
|
||||
}
|
||||
console.log(copyMachine([true, false, true], 2));
|
||||
```
|
@ -0,0 +1,65 @@
|
||||
---
|
||||
id: 587d7b7a367417b2b2512b12
|
||||
title: Copiare elementi degli array usando slice()
|
||||
challengeType: 1
|
||||
forumTopicId: 301158
|
||||
dashedName: copy-array-items-using-slice
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Il prossimo metodo che tratteremo è `slice()`. Invece di modificare un array, `slice()` copia o *estrae* un dato numero di elementi in un nuovo array, lasciando intatto l'array su cui è chiamato. `slice()` richiede solo 2 parametri — il primo è l'indice a cui iniziare l'estrazione, e il secondo è l'indice al quale interrompere l'estrazione (l'estrazione avverrà fino all'elemento a questo indice, che però non sarà incluso). Considera:
|
||||
|
||||
```js
|
||||
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
|
||||
|
||||
let todaysWeather = weatherConditions.slice(1, 3);
|
||||
```
|
||||
|
||||
`todaysWeather` avrà il valore `['snow', 'sleet']`, mentre `weatherConditions` sarà ancora `['rain', 'snow', 'sleet', 'hail', 'clear']`.
|
||||
|
||||
Di fatto, abbiamo creato un nuovo array estraendo elementi da un array esistente.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Abbiamo definito una funzione, `forecast`che prende un array come argomento. Modifica la funzione usando `slice()` per estrarre le informazioni dall'array passato come argomento e restituire un nuovo array che contiene le stringhe `warm` e `sunny`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`forecast` dovrebbe restituire `["warm", "sunny"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']),
|
||||
['warm', 'sunny']
|
||||
);
|
||||
```
|
||||
|
||||
La funzione `forecast` dovrebbe utilizzare il metodo `slice()`
|
||||
|
||||
```js
|
||||
assert(/\.slice\(/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function forecast(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
return arr;
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function forecast(arr) {
|
||||
return arr.slice(2,4);
|
||||
}
|
||||
```
|
@ -0,0 +1,218 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b16
|
||||
title: Creare array multi-dimensionali complessi
|
||||
challengeType: 1
|
||||
forumTopicId: 301159
|
||||
dashedName: create-complex-multi-dimensional-arrays
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Ottimo! Hai appena imparato un sacco di cose sugli array! Questa è stata una panoramica di livello abbastanza alto, e c'è ancora molto da imparare per lavorare con gli array, come potrai vedere nelle prossime sezioni. Ma prima di passare a studiare gli <dfn>oggetti</dfn>, diamo un'altra occhiata e vediamo come gli array possono diventare un po' più complessi di quello che abbiamo visto nelle sfide precedenti.
|
||||
|
||||
Una delle caratteristiche più potenti quando si pensa agli array come strutture di dati, è che gli array possono contenere, o anche essere completamente costituiti da altri array. Abbiamo visto array che contengono altri array nelle sfide precedenti, ma erano abbastanza semplici. Tuttavia, gli array possono contenere una profondità infinita di array che possono contenere altri array, ciascuno con i propri livelli arbitrari di profondità, e così via. In questo modo, un array può diventare molto rapidamente una struttura di dati molto complessa, conosciuta come un array <dfn>multi-dimensionale</dfn> o un array annidato. Considera l'esempio seguente:
|
||||
|
||||
```js
|
||||
let nestedArray = [
|
||||
['deep'],
|
||||
[
|
||||
['deeper'], ['deeper']
|
||||
],
|
||||
[
|
||||
[
|
||||
['deepest'], ['deepest']
|
||||
],
|
||||
[
|
||||
[
|
||||
['deepest-est?']
|
||||
]
|
||||
]
|
||||
]
|
||||
];
|
||||
```
|
||||
|
||||
L'array `deep` è annidato al secondo livello di profondità. Gli array `deeper` sono al terzo livello di profondità. Gli array `deepest` al quarto livello, e il `deepest-est?` è al quinto.
|
||||
|
||||
Anche se questo esempio può sembrare contorto, questo livello di complessità non è inaudito, e nemmeno insolito, quando si tratta di grandi quantità di dati. Tuttavia, possiamo ancora accedere molto facilmente ai livelli più profondi di un array così complesso con la notazione tra parentesi:
|
||||
|
||||
```js
|
||||
console.log(nestedArray[2][1][0][0][0]);
|
||||
```
|
||||
|
||||
Questo mostra nella console la stringa `deepest-est?`. E ora che sappiamo dove sono i dati, possiamo reimpostarli se ne abbiamo bisogno:
|
||||
|
||||
```js
|
||||
nestedArray[2][1][0][0][0] = 'deeper still';
|
||||
|
||||
console.log(nestedArray[2][1][0][0][0]);
|
||||
```
|
||||
|
||||
Ora verrà scritto `deeper still`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Abbiamo definito una variabile, `myNestedArray`, impostata su un array. Modifica `myNestedArray`, utilizzando qualsiasi combinazione di <dfn>stringhe</dfn>, <dfn>numeri</dfn>, e <dfn>booleani</dfn> per gli elementi di dati, in modo che abbia esattamente cinque livelli di profondità (ricorda, l'array più esterno è il livello 1). Da qualche parte al terzo livello, includi la stringa `deep`, al quarto livello includi la stringa `deeper`e al quinto livello includi la stringa `deepest`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myNestedArray` dovrebbe contenere solo numeri, booleani e stringhe come elementi
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
(function (arr) {
|
||||
let flattened = (function flatten(arr) {
|
||||
const flat = [].concat(...arr);
|
||||
return flat.some(Array.isArray) ? flatten(flat) : flat;
|
||||
})(arr);
|
||||
for (let i = 0; i < flattened.length; i++) {
|
||||
if (
|
||||
typeof flattened[i] !== 'number' &&
|
||||
typeof flattened[i] !== 'string' &&
|
||||
typeof flattened[i] !== 'boolean'
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
})(myNestedArray),
|
||||
true
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` dovrebbe avere esattamente 5 livelli di profondità
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
(function (arr) {
|
||||
let depth = 0;
|
||||
function arrayDepth(array, i, d) {
|
||||
if (Array.isArray(array[i])) {
|
||||
arrayDepth(array[i], 0, d + 1);
|
||||
} else {
|
||||
depth = d > depth ? d : depth;
|
||||
}
|
||||
if (i < array.length) {
|
||||
arrayDepth(array, i + 1, d);
|
||||
}
|
||||
}
|
||||
arrayDepth(arr, 0, 0);
|
||||
return depth;
|
||||
})(myNestedArray),
|
||||
4
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` dovrebbe contenere esattamente una occorrenza della stringa `deep` in un array annidato al terzo livello di profondità
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function howDeep(array, target, depth = 0) {
|
||||
return array.reduce((combined, current) => {
|
||||
if (Array.isArray(current)) {
|
||||
return combined.concat(howDeep(current, target, depth + 1));
|
||||
} else if (current === target) {
|
||||
return combined.concat(depth);
|
||||
} else {
|
||||
return combined;
|
||||
}
|
||||
}, []);
|
||||
})(myNestedArray, 'deep').length === 1 &&
|
||||
(function howDeep(array, target, depth = 0) {
|
||||
return array.reduce((combined, current) => {
|
||||
if (Array.isArray(current)) {
|
||||
return combined.concat(howDeep(current, target, depth + 1));
|
||||
} else if (current === target) {
|
||||
return combined.concat(depth);
|
||||
} else {
|
||||
return combined;
|
||||
}
|
||||
}, []);
|
||||
})(myNestedArray, 'deep')[0] === 2
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` dovrebbe contenere esattamente una occorrenza della stringa `deeper` in un array annidato al quarto livello di profondità
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function howDeep(array, target, depth = 0) {
|
||||
return array.reduce((combined, current) => {
|
||||
if (Array.isArray(current)) {
|
||||
return combined.concat(howDeep(current, target, depth + 1));
|
||||
} else if (current === target) {
|
||||
return combined.concat(depth);
|
||||
} else {
|
||||
return combined;
|
||||
}
|
||||
}, []);
|
||||
})(myNestedArray, 'deeper').length === 1 &&
|
||||
(function howDeep(array, target, depth = 0) {
|
||||
return array.reduce((combined, current) => {
|
||||
if (Array.isArray(current)) {
|
||||
return combined.concat(howDeep(current, target, depth + 1));
|
||||
} else if (current === target) {
|
||||
return combined.concat(depth);
|
||||
} else {
|
||||
return combined;
|
||||
}
|
||||
}, []);
|
||||
})(myNestedArray, 'deeper')[0] === 3
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` dovrebbe contenere esattamente una occorrenza della stringa `deepest` in un array annidato al quinto livello di profondità
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function howDeep(array, target, depth = 0) {
|
||||
return array.reduce((combined, current) => {
|
||||
if (Array.isArray(current)) {
|
||||
return combined.concat(howDeep(current, target, depth + 1));
|
||||
} else if (current === target) {
|
||||
return combined.concat(depth);
|
||||
} else {
|
||||
return combined;
|
||||
}
|
||||
}, []);
|
||||
})(myNestedArray, 'deepest').length === 1 &&
|
||||
(function howDeep(array, target, depth = 0) {
|
||||
return array.reduce((combined, current) => {
|
||||
if (Array.isArray(current)) {
|
||||
return combined.concat(howDeep(current, target, depth + 1));
|
||||
} else if (current === target) {
|
||||
return combined.concat(depth);
|
||||
} else {
|
||||
return combined;
|
||||
}
|
||||
}, []);
|
||||
})(myNestedArray, 'deepest')[0] === 4
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let myNestedArray = [
|
||||
// Only change code below this line
|
||||
['unshift', false, 1, 2, 3, 'complex', 'nested'],
|
||||
['loop', 'shift', 6, 7, 1000, 'method'],
|
||||
['concat', false, true, 'spread', 'array'],
|
||||
['mutate', 1327.98, 'splice', 'slice', 'push'],
|
||||
['iterate', 1.3849, 7, '8.4876', 'arbitrary', 'depth']
|
||||
// Only change code above this line
|
||||
];
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let myNestedArray = [
|
||||
['unshift', ['deep', ['deeper', ['deepest']]],false, 1, 2, 3, 'complex', 'nested'],
|
||||
['loop', 'shift', 6, 7, 1000, 'method'],
|
||||
['concat', false, true, 'spread', 'array'],
|
||||
['mutate', 1327.98, 'splice', 'slice', 'push'],
|
||||
['iterate', 1.3849, 7, '8.4876', 'arbitrary', 'depth']
|
||||
];
|
||||
```
|
@ -0,0 +1,111 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1e
|
||||
title: Creare l'array delle proprietà con Object.keys()
|
||||
challengeType: 1
|
||||
forumTopicId: 301160
|
||||
dashedName: generate-an-array-of-all-object-keys-with-object-keys
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Possiamo anche generare un array che contiene tutte le chiavi memorizzate in un oggetto, utilizzando il metodo `Object.keys()` e passandogli un oggetto come argomento. Questo restituirà un array con stringhe che rappresentano ogni proprietà nell'oggetto. Di nuovo, non ci sarà alcun ordine specifico per gli elementi nell'array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Termina la scrittura della funzione `getArrayOfUsers` in modo che restituisca un array contenente tutte le proprietà nell'oggetto che riceve come argomento.
|
||||
|
||||
# --hints--
|
||||
|
||||
L'oggetto `users` dovrebbe contenere solo le chiavi `Alan`, `Jeff`, `Sarah` e `Ryan`
|
||||
|
||||
```js
|
||||
assert(
|
||||
'Alan' in users &&
|
||||
'Jeff' in users &&
|
||||
'Sarah' in users &&
|
||||
'Ryan' in users &&
|
||||
Object.keys(users).length === 4
|
||||
);
|
||||
```
|
||||
|
||||
La funzione `getArrayOfUsers` dovrebbe restituire un array che contiene tutte le chiavi nell'oggetto `users`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
users.Sam = {};
|
||||
users.Lewis = {};
|
||||
let R = getArrayOfUsers(users);
|
||||
return (
|
||||
R.indexOf('Alan') !== -1 &&
|
||||
R.indexOf('Jeff') !== -1 &&
|
||||
R.indexOf('Sarah') !== -1 &&
|
||||
R.indexOf('Ryan') !== -1 &&
|
||||
R.indexOf('Sam') !== -1 &&
|
||||
R.indexOf('Lewis') !== -1
|
||||
);
|
||||
})() === true
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let users = {
|
||||
Alan: {
|
||||
age: 27,
|
||||
online: false
|
||||
},
|
||||
Jeff: {
|
||||
age: 32,
|
||||
online: true
|
||||
},
|
||||
Sarah: {
|
||||
age: 48,
|
||||
online: false
|
||||
},
|
||||
Ryan: {
|
||||
age: 19,
|
||||
online: true
|
||||
}
|
||||
};
|
||||
|
||||
function getArrayOfUsers(obj) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
console.log(getArrayOfUsers(users));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let users = {
|
||||
Alan: {
|
||||
age: 27,
|
||||
online: false
|
||||
},
|
||||
Jeff: {
|
||||
age: 32,
|
||||
online: true
|
||||
},
|
||||
Sarah: {
|
||||
age: 48,
|
||||
online: false
|
||||
},
|
||||
Ryan: {
|
||||
age: 19,
|
||||
online: true
|
||||
}
|
||||
};
|
||||
|
||||
function getArrayOfUsers(obj) {
|
||||
return Object.keys(obj);
|
||||
}
|
||||
|
||||
console.log(getArrayOfUsers(users));
|
||||
```
|
@ -0,0 +1,138 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b15
|
||||
title: Iterare attraverso tutti gli oggetti di un array utilizzando i cicli for
|
||||
challengeType: 1
|
||||
forumTopicId: 301161
|
||||
dashedName: iterate-through-all-an-arrays-items-using-for-loops
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A volte, quando si lavora con gli array, è molto utile essere in grado di iterare attraverso ogni elemento per trovare uno o più elementi di cui potremmo aver bisogno, o per manipolare un array basandoci sugli elementi che soddisfano una determinata serie di criteri. JavaScript offre diversi metodi integrati, ognuno dei quali itera sugli array in modo leggermente differente dagli altri per ottenere risultati diversi (come `every()`, `forEach()`, `map()`, etc.), tuttavia la tecnica più flessibile e che ci offre la massima quantità di controllo è un semplice ciclo `for`.
|
||||
|
||||
Considera quanto segue:
|
||||
|
||||
```js
|
||||
function greaterThanTen(arr) {
|
||||
let newArr = [];
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
if (arr[i] > 10) {
|
||||
newArr.push(arr[i]);
|
||||
}
|
||||
}
|
||||
return newArr;
|
||||
}
|
||||
|
||||
greaterThanTen([2, 12, 8, 14, 80, 0, 1]);
|
||||
```
|
||||
|
||||
Utilizzando un ciclo `for`, questa funzione itera attraverso ogni elemento dell'array, vi accede e lo sottopone a un semplice test che abbiamo creato. In questo modo, abbiamo determinato facilmente e in maniera schematica quali dati sono maggiori di `10`, e abbiamo restituito un nuovo array, `[12, 14, 80]`, contenente questi elementi.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Abbiamo definito una funzione, `filteredArray`, che richiede come argomenti `arr`, un array annidato, e `elem` e restituisce un nuovo array. `elem` rappresenta un elemento che potrebbe oppure no essere presente in uno o più degli array annidati dentro `arr`. Modifica la funzione usando un ciclo `for` per restituire una versione filtrata dell'array passato, in modo che qualsiasi array annidato all'interno di `arr` contenente `elem` venga rimosso.
|
||||
|
||||
# --hints--
|
||||
|
||||
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` dovrebbe restituire `[[10, 8, 3], [14, 6, 23]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
filteredArray(
|
||||
[
|
||||
[10, 8, 3],
|
||||
[14, 6, 23],
|
||||
[3, 18, 6]
|
||||
],
|
||||
18
|
||||
),
|
||||
[
|
||||
[10, 8, 3],
|
||||
[14, 6, 23]
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2)` dovrebbe restituire `[["flutes", 4]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
filteredArray(
|
||||
[
|
||||
['trumpets', 2],
|
||||
['flutes', 4],
|
||||
['saxophones', 2]
|
||||
],
|
||||
2
|
||||
),
|
||||
[['flutes', 4]]
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([["amy", "beth", "sam"], ["dave", "sean", "peter"]], "peter")` dovrebbe restituire `[["amy", "beth", "sam"]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
filteredArray(
|
||||
[
|
||||
['amy', 'beth', 'sam'],
|
||||
['dave', 'sean', 'peter']
|
||||
],
|
||||
'peter'
|
||||
),
|
||||
[['amy', 'beth', 'sam']]
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` dovrebbe restituire `[]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
filteredArray(
|
||||
[
|
||||
[3, 2, 3],
|
||||
[1, 6, 3],
|
||||
[3, 13, 26],
|
||||
[19, 3, 9]
|
||||
],
|
||||
3
|
||||
),
|
||||
[]
|
||||
);
|
||||
```
|
||||
|
||||
La funzione `filteredArray` dovrebbe utilizzare un ciclo `for`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(filteredArray.toString().search(/for/), -1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function filteredArray(arr, elem) {
|
||||
let newArr = [];
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
return newArr;
|
||||
}
|
||||
|
||||
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function filteredArray(arr, elem) {
|
||||
let newArr = [];
|
||||
for (let i = 0; i<arr.length; i++) {
|
||||
if (arr[i].indexOf(elem) < 0) {
|
||||
newArr.push(arr[i]);
|
||||
}
|
||||
}
|
||||
return newArr;
|
||||
}
|
||||
```
|
@ -0,0 +1,138 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1d
|
||||
title: Iterare attraverso le chiavi di un oggetto con l'istruzione for...in
|
||||
challengeType: 1
|
||||
forumTopicId: 301162
|
||||
dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A volte potrebbe essere necessario iterare attraverso tutte le chiavi di un oggetto. Ciò richiede una sintassi specifica in JavaScript chiamata istruzione <dfn>for...in</dfn>. Per il nostro oggetto `users`, questo potrebbe assomigliare a:
|
||||
|
||||
```js
|
||||
for (let user in users) {
|
||||
console.log(user);
|
||||
}
|
||||
```
|
||||
|
||||
Questo scriverebbe `Alan`, `Jeff`, `Sarah` e `Ryan` sulla console - ogni valore sulla propria linea.
|
||||
|
||||
In questa dichiarazione abbiamo definito una variabile `user`, e come puoi vedere, mentre l'iterazione prosegue attraverso l'oggetto, ad ogni ripetizione la variabile viene reimpostata a ciascuna delle chiavi, risultando nella stampa del nome di ogni utente sulla console.
|
||||
|
||||
**NOTA:** Gli oggetti non mantengono un ordine sulle chiavi memorizzate come fanno gli arrays; di conseguenza la posizione di una chiave in un oggetto, o l'ordine relativo in cui appare, è irrilevante quando ci si riferisce a tale chiave o vi si accede.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Abbiamo definito una funzione `countOnline` che accetta un argomento (un oggetto users). Usa un'instruzione <dfn>for...in</dfn> all'interno di questa funzione per iterare attraverso l'oggetto users passato alla funzione e restituire il numero di utenti la cui proprietà `online` è impostata a `true`. Un esempio di oggetto users che potrebbe essere passato a `countOnline` è mostrato qui sotto. Ogni utente avrà una proprietà `online` con un valore `true` o `false`.
|
||||
|
||||
```js
|
||||
{
|
||||
Alan: {
|
||||
online: false
|
||||
},
|
||||
Jeff: {
|
||||
online: true
|
||||
},
|
||||
Sarah: {
|
||||
online: false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
# --hints--
|
||||
|
||||
La funzione `countOnline` dovrebbe utilizzare un'istruzione `for in` per iterare attraverso le chiavi dell'oggetto passato come argomento.
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(
|
||||
/for\s*\(\s*(var|let|const)\s+[a-zA-Z_$]\w*\s+in\s+[a-zA-Z_$]\w*\s*\)/
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
La funzione `countOnline` dovrebbe restituire `1` quando le viene passato l'oggetto `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }`
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj1) === 1);
|
||||
```
|
||||
|
||||
La funzione `countOnline` dovrebbe restituire `2` quando le viene passato l'oggetto `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }`
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj2) === 2);
|
||||
```
|
||||
|
||||
La funzione `countOnline` dovrebbe restituire `0` quando le viene passato l'oggetto `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }`
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj3) === 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const usersObj1 = {
|
||||
Alan: {
|
||||
online: false
|
||||
},
|
||||
Jeff: {
|
||||
online: true
|
||||
},
|
||||
Sarah: {
|
||||
online: false
|
||||
}
|
||||
}
|
||||
|
||||
const usersObj2 = {
|
||||
Alan: {
|
||||
online: true
|
||||
},
|
||||
Jeff: {
|
||||
online: false
|
||||
},
|
||||
Sarah: {
|
||||
online: true
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const usersObj3 = {
|
||||
Alan: {
|
||||
online: false
|
||||
},
|
||||
Jeff: {
|
||||
online: false
|
||||
},
|
||||
Sarah: {
|
||||
online: false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function countOnline(usersObj) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function countOnline(usersObj) {
|
||||
let online = 0;
|
||||
for(let user in usersObj){
|
||||
if(usersObj[user].online) {
|
||||
online++;
|
||||
}
|
||||
}
|
||||
return online;
|
||||
}
|
||||
```
|
@ -0,0 +1,112 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1f
|
||||
title: Modificare un array memorizzato in un oggetto
|
||||
challengeType: 1
|
||||
forumTopicId: 301163
|
||||
dashedName: modify-an-array-stored-in-an-object
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Adesso hai visto tutte le operazioni di base per gli oggetti JavaScript. Puoi aggiungere, modificare e rimuovere coppie chiave-valore, controllare se una proprietà esiste e iterare su tutte le chiavi di un oggetto. Continuando a conoscere JavaScript vedrai applicazioni ancora più versatili degli oggetti. Inoltre, le lezioni di Strutture Dati nella sezione Colloquio di Lavoro per Programmatori del curriculum coprono anche gli oggetti ES6 <dfn>Map</dfn> e <dfn>Set</dfn>, entrambi i quali sono simili a oggetti ordinari, ma forniscono alcune caratteristiche aggiuntive. Ora che hai imparato le basi di array e oggetti, sei pienamente preparato per iniziare ad affrontare problemi più complessi utilizzando JavaScript!
|
||||
|
||||
# --instructions--
|
||||
|
||||
Dai un'occhiata all'oggetto che abbiamo fornito nell'editor di codice. L'oggetto `user` contiene tre chiavi. La chiave `data` contiene cinque chiavi, una delle quali contiene un array di `friends` (amici). Da questo puoi vedere quanto gli oggetti siano flessibili come strutture di dati. Abbiamo iniziato a scrivere una funzione `addFriend`. Finisci di scriverla in modo che prenda un oggetto `user`, aggiunga il nome dell'argomento `friend` all'array memorizzato in `user.data.friends` e restituisca questo array.
|
||||
|
||||
# --hints--
|
||||
|
||||
L'oggetto `user` dovrebbe avere le chiavi `name`, `age` e `data`.
|
||||
|
||||
```js
|
||||
assert('name' in user && 'age' in user && 'data' in user);
|
||||
```
|
||||
|
||||
La funzione `addFriend` dovrebbe ricevere un oggetto `user` e una stringa `friend` come argomenti e aggiungere l'amico all'array `friends` nell'oggetto `user`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
let L1 = user.data.friends.length;
|
||||
addFriend(user, 'Sean');
|
||||
let L2 = user.data.friends.length;
|
||||
return L2 === L1 + 1;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
`addFriend(user, "Pete")` dovrebbe restituire `["Sam", "Kira", "Tomo", "Pete"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
(function () {
|
||||
delete user.data.friends;
|
||||
user.data.friends = ['Sam', 'Kira', 'Tomo'];
|
||||
return addFriend(user, 'Pete');
|
||||
})(),
|
||||
['Sam', 'Kira', 'Tomo', 'Pete']
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let user = {
|
||||
name: 'Kenneth',
|
||||
age: 28,
|
||||
data: {
|
||||
username: 'kennethCodesAllDay',
|
||||
joinDate: 'March 26, 2016',
|
||||
organization: 'freeCodeCamp',
|
||||
friends: [
|
||||
'Sam',
|
||||
'Kira',
|
||||
'Tomo'
|
||||
],
|
||||
location: {
|
||||
city: 'San Francisco',
|
||||
state: 'CA',
|
||||
country: 'USA'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function addFriend(userObj, friend) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
console.log(addFriend(user, 'Pete'));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let user = {
|
||||
name: 'Kenneth',
|
||||
age: 28,
|
||||
data: {
|
||||
username: 'kennethCodesAllDay',
|
||||
joinDate: 'March 26, 2016',
|
||||
organization: 'freeCodeCamp',
|
||||
friends: [
|
||||
'Sam',
|
||||
'Kira',
|
||||
'Tomo'
|
||||
],
|
||||
location: {
|
||||
city: 'San Francisco',
|
||||
state: 'CA',
|
||||
country: 'USA'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function addFriend(userObj, friend) {
|
||||
userObj.data.friends.push(friend);
|
||||
return userObj.data.friends;
|
||||
}
|
||||
```
|
@ -0,0 +1,101 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b19
|
||||
title: Modificare un oggetto annidato in un altro oggetto
|
||||
challengeType: 1
|
||||
forumTopicId: 301164
|
||||
dashedName: modify-an-object-nested-within-an-object
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Diamo adesso un'occhiata ad un oggetto leggermente più complesso. Le proprietà dell'oggetto possono essere annidate ad una profondità arbitraria, e i loro valori possono essere qualsiasi tipo di dati supportato da JavaScript, inclusi array ed altri oggetti. Considera quanto segue:
|
||||
|
||||
```js
|
||||
let nestedObject = {
|
||||
id: 28802695164,
|
||||
date: 'December 31, 2016',
|
||||
data: {
|
||||
totalUsers: 99,
|
||||
online: 80,
|
||||
onlineStatus: {
|
||||
active: 67,
|
||||
away: 13,
|
||||
busy: 8
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
`nestedObject` ha tre proprietà: `id` (il valore è un numero), `date` (il valore è una stringa) e `data` (il valore è un oggetto con la propria struttura annidata). Anche se le strutture possono diventare rapidamente complesse, è ancora possibile utilizzare le stesse notazioni per accedere alle informazioni di cui abbiamo bisogno. Per assegnare il valore `10` alla proprietà `busy` dell'oggetto annidato `onlineStatus`, usiamo la notazione a punti per fare riferimento alla proprietà:
|
||||
|
||||
```js
|
||||
nestedObject.data.onlineStatus.busy = 10;
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Qui abbiamo definito un oggetto `userActivity`che include un altro oggetto annidato al suo interno. Imposta il valore della chiave `online` su `45`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`userActivity` dovrebbe avere le proprità `id`, `date` e `data`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
'id' in userActivity && 'date' in userActivity && 'data' in userActivity
|
||||
);
|
||||
```
|
||||
|
||||
`userActivity` dovrebbe avere la proprietà `data` impostata su un oggetto con chiavi `totalUsers` e `online`.
|
||||
|
||||
```js
|
||||
assert('totalUsers' in userActivity.data && 'online' in userActivity.data);
|
||||
```
|
||||
|
||||
La proprietà `online` annidata nella chiave `data` di `userActivity` dovrebbe essere impostata a `45`
|
||||
|
||||
```js
|
||||
assert(userActivity.data.online === 45);
|
||||
```
|
||||
|
||||
La proprietà `online` dovrebbe essere impostata usando la notazione a punti o a parentesi.
|
||||
|
||||
```js
|
||||
assert.strictEqual(code.search(/online: 45/), -1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let userActivity = {
|
||||
id: 23894201352,
|
||||
date: 'January 1, 2017',
|
||||
data: {
|
||||
totalUsers: 51,
|
||||
online: 42
|
||||
}
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
console.log(userActivity);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let userActivity = {
|
||||
id: 23894201352,
|
||||
date: 'January 1, 2017',
|
||||
data: {
|
||||
totalUsers: 51,
|
||||
online: 42
|
||||
}
|
||||
};
|
||||
|
||||
userActivity.data.online = 45;
|
||||
```
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b0f
|
||||
title: Rimuovere elementi da un array con pop() e shift()
|
||||
challengeType: 1
|
||||
forumTopicId: 301165
|
||||
dashedName: remove-items-from-an-array-with-pop-and-shift
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Sia `push()` che `unshift()` hanno metodi corrispondenti che sono quasi funzionalmente opposti: `pop()` e `shift()`. Come forse avrai già indovinato, invece di aggiungere, `pop()` *rimuove* un elemento dalla fine di un array, mentre `shift()` rimuove un elemento dall'inizio. La differenza chiave tra `pop()` e `shift()` e i loro cugini `push()` e `unshift()`, è che nessuno dei due metodi richiede parametri, e ognuno permette che l'array venga modificato di un solo elemento per volta.
|
||||
|
||||
Diamo un'occhiata:
|
||||
|
||||
```js
|
||||
let greetings = ['whats up?', 'hello', 'see ya!'];
|
||||
|
||||
greetings.pop();
|
||||
```
|
||||
|
||||
`greetings` avrà il valore `['whats up?', 'hello']`.
|
||||
|
||||
```js
|
||||
greetings.shift();
|
||||
```
|
||||
|
||||
`greetings` avrà il valore `['hello']`.
|
||||
|
||||
Con entrambi i metodi possiamo anche restituire il valore dell'elemento rimosso in questo modo:
|
||||
|
||||
```js
|
||||
let popped = greetings.pop();
|
||||
```
|
||||
|
||||
`greetings` avrà il valore `[]` e `popped` avrà il valore `hello`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Abbiamo definito una funzione, `popShift`, che prende un array come argomento e restituisce un nuovo array. Modifica la funzione, usando `pop()` e `shift()`, per rimuovere il primo e l'ultimo elemento dell'array passato come argomento, e assegna gli elementi rimossi alle loro variabili corrispondenti, in modo che l'array restituito contenga i loro valori.
|
||||
|
||||
# --hints--
|
||||
|
||||
`popShift(["challenge", "is", "not", "complete"])` dovrebbe restituire `["challenge", "complete"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
|
||||
'challenge',
|
||||
'complete'
|
||||
]);
|
||||
```
|
||||
|
||||
La funzione `popShift` dovrebbe utilizzare il metodo `pop()`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1);
|
||||
```
|
||||
|
||||
La funzione `popShift` dovrebbe utilizzare il metodo `shift()`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function popShift(arr) {
|
||||
let popped; // Change this line
|
||||
let shifted; // Change this line
|
||||
return [shifted, popped];
|
||||
}
|
||||
|
||||
console.log(popShift(['challenge', 'is', 'not', 'complete']));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function popShift(arr) {
|
||||
let popped = arr.pop(); // Change this line
|
||||
let shifted = arr.shift(); // Change this line
|
||||
return [shifted, popped];
|
||||
}
|
||||
```
|
@ -0,0 +1,87 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b10
|
||||
title: Rimuovere elementi usando splice()
|
||||
challengeType: 1
|
||||
forumTopicId: 301166
|
||||
dashedName: remove-items-using-splice
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Ok, quindi abbiamo imparato a rimuovere gli elementi dall'inizio e dalla fine degli array usando `shift()` e `pop()`, ma cosa succede se vogliamo rimuovere un elemento da qualche parte nel mezzo? O rimuovere più di un elemento alla volta? Beh, ecco dove entra in gioco `splice()`. `splice()` ci permette di fare proprio questo: **rimuovere qualunque numero di elementi consecutivi** da qualsiasi punto di un array.
|
||||
|
||||
`splice()` può richiedere fino a 3 parametri, ma per ora ci concentreremo solo sui primi 2. I primi due parametri di `splice()` sono interi che rappresentano indici, o posizioni, dell'array su cui viene chiamato `splice()`. E ricorda, gli array sono *indicizzati a zero*, quindi per indicare il primo elemento di un array, useremo `0`. Il primo parametro di `splice()`rappresenta l'indice dell'array da cui iniziare a rimuovere gli elementi, mentre il secondo parametro indica il numero di elementi da eliminare. Ad esempio:
|
||||
|
||||
```js
|
||||
let array = ['today', 'was', 'not', 'so', 'great'];
|
||||
|
||||
array.splice(2, 2);
|
||||
```
|
||||
|
||||
Qui rimuoviamo 2 elementi a partire dal terzo (all'indice 2). `array` avrà il valore `['today', 'was', 'great']`.
|
||||
|
||||
`splice()` non solo modifica l'array su cui viene chiamato, ma restituisce anche un nuovo array contenente il valore degli elementi rimossi:
|
||||
|
||||
```js
|
||||
let array = ['I', 'am', 'feeling', 'really', 'happy'];
|
||||
|
||||
let newArray = array.splice(3, 2);
|
||||
```
|
||||
|
||||
`newArray` ha il valore `['really', 'happy']`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Abbiamo inizializzato un array `arr`. Usa `splice()` per rimuovere gli elementi da `arr`, in modo che contenga solo elementi la cui somma sia `10`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Non devi cambiare la riga originale `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
__helpers.removeWhiteSpace(code).match(/constarr=\[2,4,5,1,7,5,2,1\];?/)
|
||||
);
|
||||
```
|
||||
|
||||
`arr` dovrebbe contenere solo elementi la cui somma è `10`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
arr.reduce((a, b) => a + b),
|
||||
10
|
||||
);
|
||||
```
|
||||
|
||||
Il tuo codice dovrebbe utilizzare il metodo `splice()` su `arr`.
|
||||
|
||||
```js
|
||||
assert(__helpers.removeWhiteSpace(code).match(/arr\.splice\(/));
|
||||
```
|
||||
|
||||
Splice dovrebbe solo rimuovere elementi da `arr` e non aggiungere altri elementi a `arr`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
!__helpers.removeWhiteSpace(code).match(/arr\.splice\(\d+,\d+,\d+.*\)/g)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
const arr = [2, 4, 5, 1, 7, 5, 2, 1];
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
console.log(arr);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const arr = [2, 4, 5, 1, 7, 5, 2, 1];
|
||||
arr.splice(1, 4);
|
||||
```
|
@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 587d7b7e367417b2b2512b20
|
||||
title: Usare un array per memorizzare una collezione di dati
|
||||
challengeType: 1
|
||||
forumTopicId: 301167
|
||||
dashedName: use-an-array-to-store-a-collection-of-data
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Di seguito è riportato un esempio della più semplice implementazione di una struttura dati ad array. Questo è conosciuto come <dfn>array uni-dimensionale</dfn>, il che significa che ha un solo livello, o che non ha altri array annidati al suo interno. Nota che contiene <dfn>booleani</dfn>, <dfn>stringhe</dfn> e <dfn>numeri</dfn>, tra gli altri tipi di dati JavaScript validi:
|
||||
|
||||
```js
|
||||
let simpleArray = ['one', 2, 'three', true, false, undefined, null];
|
||||
console.log(simpleArray.length);
|
||||
```
|
||||
|
||||
La chiamata `console.log` stampa `7`.
|
||||
|
||||
Tutti gli array hanno una proprietà di lunghezza, che come mostrato sopra, può essere facilmente accessibile con la sintassi `Array.length`. Un'implementazione più complessa di un array può essere vista qui sotto. Questo è conosciuto come <dfn>array multi-dimensionale</dfn>, e si tratta di un array che contiene altri array. Nota che questo array contiene anche <dfn>oggetti</dfn> JavaScript, che esamineremo molto attentamente nella nostra prossima sezione, ma per ora, tutto quello che devi sapere è che gli array sono anche in grado di memorizzare oggetti complessi.
|
||||
|
||||
```js
|
||||
let complexArray = [
|
||||
[
|
||||
{
|
||||
one: 1,
|
||||
two: 2
|
||||
},
|
||||
{
|
||||
three: 3,
|
||||
four: 4
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
a: "a",
|
||||
b: "b"
|
||||
},
|
||||
{
|
||||
c: "c",
|
||||
d: "d"
|
||||
}
|
||||
]
|
||||
];
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Abbiamo definito una variabile chiamata `yourArray`. Completa la dichiarazione assegnando alla variabile `yourArray` un array di almeno 5 elementi di lunghezza. Il tuo array dovrebbe contenere almeno una <dfn>stringa</dfn>, un <dfn>numero</dfn>e un <dfn>booleano</dfn>.
|
||||
|
||||
# --hints--
|
||||
|
||||
`yourArray` dovrebbe essere un array.
|
||||
|
||||
```js
|
||||
assert.strictEqual(Array.isArray(yourArray), true);
|
||||
```
|
||||
|
||||
`yourArray` dovrebbe essere lungo almeno 5 elementi.
|
||||
|
||||
```js
|
||||
assert.isAtLeast(yourArray.length, 5);
|
||||
```
|
||||
|
||||
`yourArray` dovrebbe contenere almeno un valore di tipo `boolean`.
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'boolean').length >= 1);
|
||||
```
|
||||
|
||||
`yourArray` dovrebbe contenere almeno un valore `number`.
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'number').length >= 1);
|
||||
```
|
||||
|
||||
`yourArray` dovrebbe contenere almeno un valore di tipo `string`.
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'string').length >= 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let yourArray; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let yourArray = ['a string', 100, true, ['one', 2], 'another string'];
|
||||
```
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b1b
|
||||
title: Utilizzare la parola chiave delete per rimuovere proprietà da un oggetto
|
||||
challengeType: 1
|
||||
forumTopicId: 301168
|
||||
dashedName: use-the-delete-keyword-to-remove-object-properties
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Ora sai cosa sono gli oggetti e quali sono le loro caratteristiche e vantaggi di base. In breve, si tratta di archivi di coppie chiave-valore che dispongono di un modo flessibile e intuitivo di strutturare i dati, ***e***, assicurano un tempo di ricerca molto veloce. Nel resto di queste sfide, descriveremo diverse operazioni comuni che puoi eseguire sugli oggetti in modo che tu possa acquisire dimestichezza nell'applicare queste utili strutture di dati nei tuoi programmi.
|
||||
|
||||
Nelle sfide precedenti, abbiamo sia aggiunto che modificato le coppie chiave-valore di un oggetto. Qui vedremo come possiamo *rimuovere* una coppia chiave-valore da un oggetto.
|
||||
|
||||
Rivisitiamo il nostro esempio di oggetto `foods` un'ultima volta. Se volessimo rimuovere la chiave `apples`, possiamo eliminarla utilizzando la parola chiave `delete` in questo modo:
|
||||
|
||||
```js
|
||||
delete foods.apples;
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa la parola chiave delete per rimuovere le chiavi `oranges`, `plums`, e `strawberries` dall'oggetto `foods`.
|
||||
|
||||
# --hints--
|
||||
|
||||
L'oggetto `foods` dovrebbe avere solo tre chiavi: `apples`, `grapes`, e `bananas`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
!foods.hasOwnProperty('oranges') &&
|
||||
!foods.hasOwnProperty('plums') &&
|
||||
!foods.hasOwnProperty('strawberries') &&
|
||||
Object.keys(foods).length === 3
|
||||
);
|
||||
```
|
||||
|
||||
Le chiavi `oranges`, `plums` e `strawberries` dovrebbero essere rimosse usando `delete`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.search(/oranges:/) !== -1 &&
|
||||
code.search(/plums:/) !== -1 &&
|
||||
code.search(/strawberries:/) !== -1
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let foods = {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28,
|
||||
bananas: 13,
|
||||
grapes: 35,
|
||||
strawberries: 27
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
console.log(foods);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let foods = {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28,
|
||||
bananas: 13,
|
||||
grapes: 35,
|
||||
strawberries: 27
|
||||
};
|
||||
|
||||
delete foods.oranges;
|
||||
delete foods.plums;
|
||||
delete foods.strawberries;
|
||||
|
||||
console.log(foods);
|
||||
```
|
@ -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();
|
||||
```
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user