Skip to content

Commit dbc298f

Browse files
authored
Update article.md
1 parent 1f374b0 commit dbc298f

File tree

1 file changed

+53
-122
lines changed
  • 1-js/05-data-types/10-destructuring-assignment

1 file changed

+53
-122
lines changed

1-js/05-data-types/10-destructuring-assignment/article.md

Lines changed: 53 additions & 122 deletions
Original file line numberDiff line numberDiff line change
@@ -2,37 +2,22 @@
22

33
Le due strutture dati più utilizzate in JavaScritp sono `Object` e `Array`.
44

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.
127

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.
149

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.
2111

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.
2313

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
2915

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:
3117

3218
```js
33-
// we have an array with the name and surname
19+
// abbiamo un array con nome e cognome
3420
let arr = ["John", "Smith"]
35-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
3621

3722
*!*
3823
// assegnamento di destrutturazione
@@ -47,23 +32,19 @@ alert(surname); // Smith
4732

4833
Ora possiamo lavorare con le variabili piuttosto che con i membri dell'array.
4934

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:
5136

5237
```js run
5338
let [firstName, surname] = "John Smith".split(' ');
5439
alert(firstName); // John
5540
alert(surname); // Smith
5641
```
5742

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+
6345

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.
6748
6849
E' solo un modo breve per scrivere:
6950
```js
@@ -73,8 +54,9 @@ let surname = arr[1];
7354
```
7455
````
7556

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:
7860
7961
```js run
8062
*!*
@@ -85,29 +67,24 @@ let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic
8567
alert( title ); // Consul
8668
```
8769
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).
8971
````
9072

91-
````smart header="Funziona con qualsiasi itarabile"
73+
````smart header="Funziona con qualsiasi itarabile sulla destra"
9274
9375
... In realtà, possiamo utilizzarlo con qualsiasi iterabile, non solamente con array:
9476
9577
```js
9678
let [a, b, c] = "abc"; // ["a", "b", "c"]
9779
let [one, two, three] = new Set([1, 2, 3]);
9880
```
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-
````
10181
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+
````
10284

103-
<<<<<<< HEAD
10485
````smart header="Assegna a qualsiasi cosa ci sia dalla parte sinistra"
10586
10687
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
11188
11289
Ad esempio, la proprietà di un oggetto:
11390
```js run
@@ -120,14 +97,9 @@ alert(user.surname); // Smith
12097
12198
````
12299

123-
<<<<<<< HEAD
124-
````smart header="Cicla con .entries()"
100+
````smart header="Eseguire cicli con .entries()"
125101
126102
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
131103
132104
Possiamo utilizzarlo con la destrutturazione per eseguire cicli su chaivi/valore di un oggetto:
133105
@@ -137,123 +109,92 @@ let user = {
137109
age: 30
138110
};
139111
140-
// ciclo su chiavi e valori
112+
// ciclo su chiavi/valori
141113
*!*
142114
for (let [key, value] of Object.entries(user)) {
143115
*/!*
144116
alert(`${key}:${value}`); // name:John, poi age:30
145117
}
146118
```
147119
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+
153122
154123
```js run
155124
let user = new Map();
156125
user.set("name", "John");
157126
user.set("age", "30");
158127
159128
*!*
160-
// Map iterates as [key, value] pairs, very convenient for destructuring
129+
// Map itera le coppie [key, value], molto comodo per la destrutturazione
161130
for (let [key, value] of user) {
162131
*/!*
163132
alert(`${key}:${value}`); // name:John, then age:30
164133
}
165134
```
166135
````
167136

168-
<<<<<<< HEAD
137+
169138
```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+
175141
176142
```js run
177143
let guest = "Jane";
178144
let admin = "Pete";
179145
180-
<<<<<<< HEAD
181146
// Scambio dei valori: rende guest=Pete, admin=Jane
182-
=======
183-
// Let's swap the values: make guest=Pete, admin=Jane
184147
*!*
185-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
186148
[guest, admin] = [admin, guest];
187149
*/!*
188150
189151
alert(`${guest} ${admin}`); // Pete Jane (scambiati con successo!)
190152
```
191153

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.
196156

197-
=======
198-
We can swap more than two variables this way.
199-
````
200-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
201157

202-
### L'operatore resto '...'
158+
### L'operatore rest '...'
203159

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.
208161

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:
211163

212164
```js run
213165
let [name1, name2] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
214166

215167
alert(name1); // Julius
216168
alert(name2); // Caesar
217-
// Furher items aren't assigned anywhere
169+
// Gli elementi successivi non vengono assegnati
218170
```
219171

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 `" ... "`:
221173

222174
```js run
223175
let [name1, name2, *!*...rest*/!*] = ["Julius", "Caesar", *!*"Consul", "of the Roman Republic"*/!*];
224176
225177
*!*
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
231179
alert(rest[0]); // Consul
232180
alert(rest[1]); // of the Roman Republic
233181
alert(rest.length); // 2
234182
*/!*
235183
```
236184

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.
241185

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.
243189

244190
```js run
245191
let [name1, name2, *!*...titles*/!*] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
246192
// now titles = ["Consul", "of the Roman Republic"]
247193
```
248-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
249194

250195
### Valori di default
251196

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:
257198

258199
```js run
259200
*!*
@@ -264,7 +205,7 @@ alert(firstName); // undefined
264205
alert(surname); // undefined
265206
```
266207

267-
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 `=`:
268209

269210
```js run
270211
*!*
@@ -276,13 +217,11 @@ alert(name); // Julius (dall'array)
276217
alert(surname); // Anonymous (valore di default)
277218
```
278219

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:
280224

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
286225

287226
```js run
288227
// viene eseguito solo il prompt per il cognome
@@ -292,23 +231,19 @@ alert(name); // Julius (dall'array)
292231
alert(surname); // qualsiasi cosa provenga dal prompt
293232
```
294233

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`).
296235

297236
## Destrutturazione di oggetti
298237

299-
L'assegnamento di destrutturazione funziona allo stesso modo con gli oggetti.
238+
L'assegnamento di destrutturazione funziona anche con gli oggetti.
300239

301240
La sintassi è:
302241

303242
```js
304243
let {var1, var2} = {var1:…, var2:…}
305244
```
306245

307-
<<<<<<< HEAD
308246
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
312247

313248
Ad esempio:
314249

@@ -329,12 +264,10 @@ alert(height); // 200
329264
```
330265

331266
<<<<<<< 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:
335270

336-
The order does not matter. This works too:
337-
>>>>>>> 468e3552884851fcef331fbdfd58096652964b5f
338271

339272
```js
340273
// cambiato l'ordine delle proprietà in let {...}
@@ -343,11 +276,9 @@ let {height, width, title} = { title: "Menu", height: 200, width: 100 }
343276

344277
Il pattern alla sinistra potrebbe essere anche più complesso e specificare una mappatura tra proprietà e variabili.
345278

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:
281+
351282

352283
```js run
353284
let options = {

0 commit comments

Comments
 (0)