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,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);
|
||||
```
|
Reference in New Issue
Block a user