配列の分割代入は、配列から値を取り出す簡潔な方法です。構文は配列リテラルの式に似ていますが、右辺ではなく代入の左辺に書きます。
const frenchNumbers = ['quatre-vingts', 'quatre-vingt-dix', 'cent'];
const [french80, french90, french100] = frenchNumbers;
french80;
// => 'quatre-vingts'
french90;
// => 'quatre-vingt-dix'
french100;
// => 'cent'
変数は配列内の値に位置で対応付けられるため、分割代入の構文を使うと、1つの式で複数の変数に代入したり再代入したりできます。
let [a, b] = ['world', 'hello'];
[b, a] = [a, b];
a;
// => 'hello'
b;
// => 'world'
入れ子の配列でも同じように使えます。
let [a, b, c] = ['orange', 'purple', 'green'];
[[a, b], c] = [[c, a], b];
a;
// => 'green'
b;
// => 'orange'
c;
// => 'purple'
この構文では、対応付けの際に値を飛ばすことができます。たとえば、配列内の特定の位置を無視したいときです。
次の例では、ユーザーの名、姓、住所を含む配列を返すgetUserInfo関数があるとします。
getUserInfo();
// => ["Valerie", "Noir", "Sunny Lane 523"]
const [, , streetAddress] = getUserInfo();
streetAddress;
// => "Sunny Lane 523"
代入で配列の値をすべて使う必要もありません。
const [firstName, lastName] = getUserInfo();
firstName;
// => "Valerie"
lastName;
// => "Noir"
配列に含まれる数より多くの値を取り出すこともできます。余った変数にはundefinedが代入されます。値の個数があらかじめわからない場合に便利です。
const pickAtLeastOne = ['first choice', 'second choice'];
const [first, second, third, fourth] = pickAtLeastOne;
first;
// => "first choice"
second;
// => "second choice"
third;
// => undefined
fourth;
// => undefined
配列の分割代入では、元の配列に値がない場合に備えてデフォルト値を指定できます。
const [first, second, third = 'none selected', fourth] = pickAtLeastOne;
third;
// => 'none selected'
fourth;
// => undefined