JavaScript: object destructuring sugli array

In JavaScript l'object destructuring può essere applicato anche agli array.

JavaScript di Gabriele Romanato

In JavaScript l'object destructuring può essere applicato anche agli array.

Supponiamo di dover ricavare delle variabili da un array. Nel modo tradizionale scriveremo:


'use strict';

const arr = [1, 2];
const a = arr[0];
const b = arr[1];

console.log(a, b); // 1 2

Con l'object destructuring avremo invece:


'use strict';

const arr = [1, 2];
const [a, b] = arr;

console.log(a, b); // 1 2

Rispetto all'object destructuring sugli oggetti, in questo caso useremo le parentesi quadre per estrarre le variabili dall'array.

Commenti