配列の分割代入(Destructuring Assignment)は、ES6で導入された構文で、配列の要素を個別の変数に簡潔に代入できます。従来は array[0]、array[1] のようにインデックスで1つずつ取り出していたものが、1行でまとめて取り出せるようになります。
この記事では、基本的な使い方からデフォルト値、残余要素、変数の入れ替え、関数の戻り値での活用まで、配列の分割代入を実践的に解説します。
基本的な使い方
配列の分割代入は、左辺に [] を使って変数を並べ、右辺の配列から対応する位置の値が代入されます。
// 基本的な分割代入
const colors = ['赤', '青', '緑'];
const [first, second, third] = colors;
console.log(first); // 配列の0番目
console.log(second); // 配列の1番目
console.log(third); // 配列の2番目
// 従来の書き方との比較
const old_first = colors[0];
const old_second = colors[1];
const old_third = colors[2];
// 分割代入なら1行で済む赤
青
緑左辺の変数の順番と右辺の配列のインデックスが対応します。変数の数が配列の要素数より少なければ、残りの要素は無視されます。多ければ undefined が代入されます。
要素のスキップとデフォルト値
不要な要素はカンマだけで飛ばすことができます。また、値が undefined の場合に使うデフォルト値を指定できます。
// 要素のスキップ
const numbers = [10, 20, 30, 40, 50];
const [, , third_num] = numbers; // 1番目と2番目をスキップ
console.log('3番目:', third_num);
const [first_num, , , fourth_num] = numbers;
console.log('1番目:', first_num, '4番目:', fourth_num);
// デフォルト値
const partial = [1, 2];
const [a, b, c = 100] = partial;
console.log(a, b, c); // cはデフォルト値が使われる
// デフォルト値は undefined の場合のみ適用
const withNull = [1, null, undefined];
const [x, y = 'default', z = 'default'] = withNull;
console.log(x, y, z); // null はデフォルト値を上書きしない3番目: 30
1番目: 10 4番目: 40
1 2 100
1 null defaultデフォルト値は値が undefined の場合にのみ適用されます。null や 0、空文字列 '' は undefined ではないため、デフォルト値は使われません。この挙動はよく誤解されるポイントなので覚えておきましょう。
残余要素(rest)
スプレッド構文 ... を使うと、残りの要素をまとめて新しい配列に格納できます。
const scores = [95, 88, 72, 64, 81];
// 最初の2つを個別に、残りをまとめて取得
const [top, second_score, ...rest] = scores;
console.log('1位:', top);
console.log('2位:', second_score);
console.log('残り:', rest);
// 先頭と残りを分離するパターン
const [head, ...tail] = [1, 2, 3, 4, 5];
console.log('先頭:', head);
console.log('残り:', tail);1位: 95
2位: 88
残り: [72, 64, 81]
先頭: 1
残り: [2, 3, 4, 5]実践例
// 変数の入れ替え(一時変数が不要)
let x = 10;
let y = 20;
[x, y] = [y, x];
console.log('x:', x, 'y:', y);
// 関数の複数戻り値
function getMinMax(arr) {
const sorted = [...arr].sort((a, b) => a - b);
return [sorted[0], sorted[sorted.length - 1]];
}
const [min, max] = getMinMax([34, 12, 89, 5, 67]);
console.log('最小:', min, '最大:', max);
// 正規表現のマッチ結果
const dateStr = '2024-03-15';
const [, year, month, day] = dateStr.match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(year + '年' + month + '月' + day + '日');
// ネストした配列の分割代入
const matrix = [[1, 2], [3, 4]];
const [[a1, a2], [b1, b2]] = matrix;
console.log(a1, a2, b1, b2);x: 20 y: 10
最小: 5 最大: 89
2024年03月15日
1 2 3 4変数の入れ替えは、従来なら一時変数 temp が必要でしたが、分割代入を使えば1行で実現できます。関数から複数の値を返すパターンも、Pythonのタプルアンパックに似た直感的なコードになります。
配列の分割代入は for...of ループでも使えます。for (const [index, value] of array.entries()) { } のように書けば、インデックスと値を同時に取得できます。
... を使った残余要素は、必ず分割代入の最後に置く必要があります。const [...rest, last] = array のように途中や先頭に書くとSyntaxErrorになります。
まとめ
- 分割代入は
const [a, b, c] = arrayで配列の要素を変数に取り出せる - カンマで要素をスキップでき、
= デフォルト値で未定義時の値を指定できる ...restで残りの要素をまとめて配列として取得できる- 変数の入れ替え
[a, b] = [b, a]が1行で書ける - 関数の複数戻り値、正規表現のマッチ結果の取り出しなど活用場面は多い