You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Le due strutture dati più utilizzate in JavaScritp sono `Object` e `Array`.
4
4
5
-
<<<<<<< HEAD
6
-
Gli oggetti ci consentono di raccogliere molti pezzi di informazione in una singola entità, mentre gli array ci consentono di memorizzare collezioni ordinate. Possiamo quindi costruire un oggetto o un array e gestirlo come singola entità, oppure passarlo ad una funzione.
7
-
8
-
*L'assegnamento di destrutturazione* è una speciale sintassi che ci consente di "spacchettare" oggetti o array in un insieme di variabili, che in molti casi possono risultare più comode.
9
-
La destrutturazione inoltre funziona molto bene con le funzione complesse che richiedono molti parametri, valori di default, molto presto vedremo come gestire anche questi.
10
-
11
-
## Destrutturazione di un array
5
+
- Gli oggetti ci consentono di creare un'unica entità che memorizza elementi nel formato chiave-valore
6
+
- Gli array ci consentono di raccogliere elementi in elenchi ordinati.
12
7
13
-
Un esempio di come un array viene destrutturato in variabili:
8
+
A volte, quando li passiamo ad una funzione, potebbe non èssere necessario tutto l'oggetto/array, ma solo una parte di esso.
14
9
15
-
```js
16
-
// abbiamo un array con nome e cognome
17
-
let arr = ["Ilya", "Kantor"]
18
-
=======
19
-
- Objects allow us to create a single entity that stores data items by key.
20
-
- Arrays allow us to gather data items into an ordered list.
10
+
*L'assegnamento di destrutturazione (Destructuring assignment)* è una speciale sintassi che ci consente di "spacchettare" oggetti o array in un gruppi di variabili, questo a volte risulta molto convenente.
21
11
22
-
Although, when we pass those to a function, it may need not an object/array as a whole. It may need individual pieces.
12
+
La destrutturazione funziona alla grande anche con funzioni complesse che hanno molti parametri, valori predefiniti e così via. Presto lo vedremo.
23
13
24
-
*Destructuring assignment* is a special syntax that allows us to "unpack" arrays or objects into a bunch of variables, as sometimes that's more convenient.
25
-
26
-
Destructuring also works great with complex functions that have a lot of parameters, default values, and so on. Soon we'll see that.
27
-
28
-
## Array destructuring
14
+
## Destrutturazione di un array
29
15
30
-
Here's an example of how an array is destructured into variables:
16
+
Ecco un esempio di come un array viene destrutturato in variabili:
31
17
32
18
```js
33
-
//we have an array with the name and surname
19
+
//abbiamo un array con nome e cognome
34
20
let arr = ["John", "Smith"]
35
-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
36
21
37
22
*!*
38
23
// assegnamento di destrutturazione
@@ -47,23 +32,19 @@ alert(surname); // Smith
47
32
48
33
Ora possiamo lavorare con le variabili piuttosto che con i membri dell'array.
49
34
50
-
Risulta utile se combinata con `split` o altri metodi che ritorna un array:
35
+
Risulta utilissima se combinata con `split` o altri metodi che ritornano un array:
51
36
52
37
```js run
53
38
let [firstName, surname] ="John Smith".split('');
54
39
alert(firstName); // John
55
40
alert(surname); // Smith
56
41
```
57
42
58
-
<<<<<<< HEAD
59
-
````smart header="\"Destrutturazione\" non significa \"distruzione\"."
60
-
Viene chiamato "assegnamento di destrutturazione", perché "destrutturizza" copiando gli elementi all'interno di variabili. Ma l'array stesso non viene modificato.
61
-
=======
62
-
As you can see, the syntax is simple. There are several peculiar details though. Let's see more examples, to better understand it.
43
+
Come puoi vedere, la sintassi è semplice. Ci sono però molti dettagli peculiari. Vediamo altri esempi, per capirlo meglio.
44
+
63
45
64
-
````smart header="\"Destructuring\" does not mean \"destructive\"."
65
-
It's called "destructuring assignment," because it "destructurizes" by copying items into variables. But the array itself is not modified.
66
-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
46
+
````smart header="\"Destrutturazione\" non significa \"distruzione\"."
47
+
Viene chiamato "assegnamento di destrutturazione", perché "destrutturizza" copiando gli elementi all'interno di variabili. Ma l'array in sè non viene modificato.
67
48
68
49
E' solo un modo breve per scrivere:
69
50
```js
@@ -73,8 +54,9 @@ let surname = arr[1];
73
54
```
74
55
````
75
56
76
-
````smart header="Ignora gli elementi con la virgola"
77
-
Possono essere ignorati degli elementi dell'array inserendo una virgola:
57
+
````smart header="Ignora gli elementi usando la virgola"
58
+
59
+
Gli elementi indesiderati dell'array possono anche essere ignorati tramite una virgola aggiuntiva:
78
60
79
61
```js run
80
62
*!*
@@ -85,29 +67,24 @@ let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic
85
67
alert( title ); // Consul
86
68
```
87
69
88
-
Nel codice sopra, il secondo elemento viene ignorato, il terzo viene assegnato a `title`, il resto dell'array viene ignorato.
70
+
Nel codice sopra, il secondo elemento viene saltato, il terzo viene assegnato a `title`, il resto dell'array viene ignorato (visto che sono state inserite ulteriori variabili).
89
71
````
90
72
91
-
````smart header="Funziona con qualsiasi itarabile"
73
+
````smart header="Funziona con qualsiasi itarabile sulla destra"
92
74
93
75
... In realtà, possiamo utilizzarlo con qualsiasi iterabile, non solamente con array:
94
76
95
77
```js
96
78
let [a, b, c] = "abc"; // ["a", "b", "c"]
97
79
let [one, two, three] = new Set([1, 2, 3]);
98
80
```
99
-
That works, because internally a destructuring assignment works by iterating over the right value. It's kind of syntax sugar for calling `for..of` over the value to the right of `=` and assigning the values.
100
-
````
101
81
82
+
Funziona, perchè internamente un'assegnazione di destrutturazione lavora iterando sul valore di destra. E' una specie di "zucchero sintattico" per chiamare `for..of` sul valore a destra di `=` assegnando i valori.
83
+
````
102
84
103
-
<<<<<<< HEAD
104
85
````smart header="Assegna a qualsiasi cosa ci sia dalla parte sinistra"
105
86
106
87
Possiamo inserire qualsiasi cosa sia "assegnabile" alla sinistra.
107
-
=======
108
-
````smart header="Assign to anything at the left-side"
109
-
We can use any "assignables" at the left side.
110
-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
111
88
112
89
Ad esempio, la proprietà di un oggetto:
113
90
```js run
@@ -120,14 +97,9 @@ alert(user.surname); // Smith
120
97
121
98
````
122
99
123
-
<<<<<<< HEAD
124
-
````smart header="Cicla con .entries()"
100
+
````smart header="Eseguire cicli con .entries()"
125
101
126
102
Nel capitolo precedente abbiamo visto il metodo [Object.entries(obj)](mdn:js/Object/entries).
127
-
=======
128
-
````smart header="Looping with .entries()"
129
-
In the previous chapter we saw the [Object.entries(obj)](mdn:js/Object/entries) method.
130
-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
131
103
132
104
Possiamo utilizzarlo con la destrutturazione per eseguire cicli su chaivi/valore di un oggetto:
133
105
@@ -137,123 +109,92 @@ let user = {
137
109
age: 30
138
110
};
139
111
140
-
// ciclo su chiavi e valori
112
+
// ciclo su chiavi/valori
141
113
*!*
142
114
for (let [key, value] of Object.entries(user)) {
143
115
*/!*
144
116
alert(`${key}:${value}`); // name:John, poi age:30
145
117
}
146
118
```
147
119
148
-
<<<<<<< HEAD
149
-
...Lo stesso vale per map:
150
-
=======
151
-
The similar code for a `Map` is simpler, as it's iterable:
152
-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
120
+
Codice simile usando `Map` è più semplice, visto che è iterabile:
121
+
153
122
154
123
```js run
155
124
let user = new Map();
156
125
user.set("name", "John");
157
126
user.set("age", "30");
158
127
159
128
*!*
160
-
// Map iterates as [key, value] pairs, very convenient for destructuring
129
+
// Map itera le coppie [key, value], molto comodo per la destrutturazione
161
130
for (let [key, value] of user) {
162
131
*/!*
163
132
alert(`${key}:${value}`); // name:John, then age:30
164
133
}
165
134
```
166
135
````
167
136
168
-
<<<<<<< HEAD
137
+
169
138
```smart header="Il trucco dello scambio di varibili"
170
-
Un metodo molto conosciuto per lo scambio dei valori di due variabili:
171
-
=======
172
-
````smart header="Swap variables trick"
173
-
There's a well-known trick for swapping values of two variables using a destructuring assignment:
174
-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
139
+
c'è un trucco molto conosciuto per scambiare i valori di due variabili usando l'assegnamento di destrutturazione:
140
+
175
141
176
142
```js run
177
143
let guest = "Jane";
178
144
let admin = "Pete";
179
145
180
-
<<<<<<< HEAD
181
146
// Scambio dei valori: rende guest=Pete, admin=Jane
182
-
=======
183
-
// Let's swap the values: make guest=Pete, admin=Jane
184
147
*!*
185
-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
186
148
[guest, admin] = [admin, guest];
187
149
*/!*
188
150
189
151
alert(`${guest} ${admin}`); // Pete Jane (scambiati con successo!)
190
152
```
191
153
192
-
Qui creiamo un array temporaneo di due varibili e lo destrutturiamo immediatamente invertendo l'ordine delle variabili.
193
-
194
-
<<<<<<< HEAD
195
-
In questo modo possiamo invertire l'ordine di più di due variabili.
154
+
Nell'esempio creiamo un array temporaneo di due varibili e lo destrutturiamo immediatamente invertendo l'ordine delle variabili.
155
+
Nello stesso modo potemmo scambiare i valori di più di sue variabili.
196
156
197
-
=======
198
-
We can swap more than two variables this way.
199
-
````
200
-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
201
157
202
-
### L'operatore resto '...'
158
+
### L'operatore rest '...'
203
159
204
-
<<<<<<< HEAD
205
-
Se invece vogliamo destrutturare tutto, non solamente il primo elemento, ma raccogliere anche quello che segue -- passiamo un ulteriore parametro nella forma `"..."`:
206
-
=======
207
-
Usually, if the array is longer when the list at the left, the "extra" items are omitted.
160
+
Di solito, se l'array è più lungo della lista a sinistra, gli elementi in eccesso vengono ignorati.
208
161
209
-
For example, here only two items are taken, and the rest is just ignored:
210
-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
162
+
Ad esempio, qui vengono presi solo i primi 2 elementi, i restanti vengono semplicemente ignorati:
211
163
212
164
```js run
213
165
let [name1, name2] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
214
166
215
167
alert(name1); // Julius
216
168
alert(name2); // Caesar
217
-
// Furher items aren't assigned anywhere
169
+
//Gli elementi successivi non vengono assegnati
218
170
```
219
171
220
-
If we'd like also to gather all that follows -- we can add one more parameter that gets "the rest" using three dots `"..."`:
172
+
Se vogliamo anche ottenere tutto ciò che segue, possiamo aggiungere un altro parametro che raccoglie "il resto" utilizzando tre punti`"..."`:
221
173
222
174
```js run
223
175
let [name1, name2, *!*...rest*/!*] = ["Julius", "Caesar", *!*"Consul", "of the Roman Republic"*/!*];
224
176
225
177
*!*
226
-
<<<<<<< HEAD
227
-
// Da notare che il tipo di `rest` è Array.
228
-
=======
229
-
// rest is array of items, starting from the 3rd one
230
-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
178
+
// rest è un array di elementi, che parte dal terzo
231
179
alert(rest[0]); // Consul
232
180
alert(rest[1]); // of the Roman Republic
233
181
alert(rest.length); // 2
234
182
*/!*
235
183
```
236
184
237
-
<<<<<<< HEAD
238
-
La variabile `rest` è un array dei valori dell'array rimanenti. Possiamo utilizzare qualsiasi altro nome di variabile al posto di `rest`, è sufficiente accertarsi di inserire i tre punti prima del nome.
239
-
=======
240
-
The value of `rest` is the array of the remaining array elements.
241
185
242
-
We can use any other variable name in place of `rest`, just make sure it has three dots before it and goes last in the destructuring assignment.
186
+
La variabile `rest` è un array dei valori dell'array rimanenti.
187
+
188
+
Possiamo utilizzare qualsiasi altro nome di variabile al posto di `rest`, è sufficiente accertarsi di inserire i tre punti prima del nome e di posizionarlo alla fine nell'assegnamento di destrutturazione.
243
189
244
190
```js run
245
191
let [name1, name2, *!*...titles*/!*] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
246
192
// now titles = ["Consul", "of the Roman Republic"]
247
193
```
248
-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
249
194
250
195
### Valori di default
251
196
252
-
<<<<<<< HEAD
253
-
Se ci sono meno valori nell'array delle variabili da assegnare, non ci sarà alcun errore. I valori assenti vengono considerati undefined:
254
-
=======
255
-
If the array is shorter than the list of variables at the left, there'll be no errors. Absent values are considered undefined:
256
-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
197
+
Se ci sono meno elementi nell'array delle variabili da assegnare, non ci sarà alcun errore. I valori assenti vengono considerati undefined:
Se volessimo utilizzare un nostro valore di "default", potremmo fornirlo con la sintassi `=`:
208
+
Se volessimo assegnare un nostro valore di "default", potremmo indicarlo con la sintassi `=`:
268
209
269
210
```js run
270
211
*!*
@@ -276,13 +217,11 @@ alert(name); // Julius (dall'array)
276
217
alert(surname); // Anonymous (valore di default)
277
218
```
278
219
279
-
I valori di default possono essere anche espressioni complesse o anche delle chiamate a funzione. Verranno presi in considerazione solamente se non verrà fornito alcun valore.
220
+
I valori di default possono essere anche espressioni complesse o chiamate a funzione. Verranno presi in considerazione solamente se non verrà fornito alcun valore.
221
+
222
+
223
+
Ad esempio, qui usiamo la funzione `prompt` per due defaults:
280
224
281
-
<<<<<<< HEAD
282
-
Ad esempio, qui usiamo la funzione `prompt` come default. La chiamata avverrà solamente nel secondo caso:
283
-
=======
284
-
For instance, here we use the `prompt` function for two defaults:
285
-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
286
225
287
226
```js run
288
227
// viene eseguito solo il prompt per il cognome
@@ -292,23 +231,19 @@ alert(name); // Julius (dall'array)
292
231
alert(surname); // qualsiasi cosa provenga dal prompt
293
232
```
294
233
295
-
Please note: the `prompt` will run only for the missing value (`surname`).
234
+
Attenzione: la funzione `prompt`verrà eseguita solo per il valore vancante (`surname`).
296
235
297
236
## Destrutturazione di oggetti
298
237
299
-
L'assegnamento di destrutturazione funziona allo stesso modo con gli oggetti.
238
+
L'assegnamento di destrutturazione funziona anche con gli oggetti.
300
239
301
240
La sintassi è:
302
241
303
242
```js
304
243
let {var1, var2} = {var1:…, var2:…}
305
244
```
306
245
307
-
<<<<<<< HEAD
308
246
Abbiamo un oggetto alla destra dell'assegnazione, che vogliamo dividere in variabili. Nel lato sinistro abbiamo un "pattern" di proprietà corrispondenti. In questo semplice caso, abbiamo una lista di variabili raggruppate tra parentesi `{...}`.
309
-
=======
310
-
We should have an existing object at the right side, that we want to split into variables. The left side contains an object-like "pattern" for corresponding properties. In the simplest case, that's a list of variable names in `{...}`.
311
-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
312
247
313
248
Ad esempio:
314
249
@@ -329,12 +264,10 @@ alert(height); // 200
329
264
```
330
265
331
266
<<<<<<< HEAD
332
-
Le proprietà `options.title`, `options.width` e `options.height` vengono assegnate alle variabili corrispondenti. L'ordine non ha importanza. Questo codice funzionerebbe allo stesso modo:
333
-
=======
334
-
Properties `options.title`, `options.width` and `options.height` are assigned to the corresponding variables.
267
+
Le proprietà `options.title`, `options.width` e `options.height` vengono assegnate alle variabili corrispondenti.
268
+
269
+
L'ordine non ha importanza. Questo codice funzionerebbe comunque:
Il pattern alla sinistra potrebbe essere anche più complesso e specificare una mappatura tra proprietà e variabili.
345
278
346
-
<<<<<<< HEAD
347
-
Se volessimo assegnare una proprietà ad una variabile con un altro nome, ad esempio, la proprietà `options.width` vogliamo inserirla in una variabile chiamata `w`, allora possiamo specificarlo con i due punti:
348
-
=======
349
-
If we want to assign a property to a variable with another name, for instance, make `options.width` go into the variable named `w`, then we can set the variable name using a colon:
350
-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
279
+
280
+
Se volessimo assegnare una proprietà ad una variabile con un altro nome, ad esempio, la proprietà `options.width` vogliamo assegnarla ad una variabile chiamata `w`, allora possiamo specificarlo con i due punti:
0 commit comments