JavaScript / コードを試す
配列を作る — Array.from() / Array.of() / new Array()
new Array(3) が作るのは「穴が3つ」で、map() が動きません。Array.from() との違い、 fill() で同じオブジェクトが共有される罠、連番の作り方まで実行して確かめます。
固定例はNode 24.22.3の実行記録を照合しています()。下の入力欄の結果は今回の実行で確認してください。
コードを編集して試す
ブラウザー内で実行します。コードの送信・自動実行・自動保存はしません。このタブを閉じると入力は失われます。機密情報は入力しないでください。
8,192 UTF-8 byte・実行1.5秒・出力60行/8KiB以内。Ctrl / ⌘ + Enterでも実行できます。
パネルを開くと編集できます。
現在の入力は未実行です。
入力中のコードをこの例へ置き換えます。
実行画面や検索画面の間の通常クリックでは入力をこのタブのRAMで保持します。元の教材は別タブで開きます。再読み込み・タブ終了ではRAMの入力は失われます。
Array.from() — 何からでも配列にする
console.log(Array.from('あい')); console.log(Array.from(new Set([1, 1, 2]))); console.log(Array.from([1, 2], (n) => n * 10));
[ 'あ', 'い' ] [ 1, 2 ] [ 10, 20 ]
第2引数に関数を渡すと、その場で加工できます。
Array.from(x).map(f) と同じですが、中間の配列を作りません。
対象は反復可能なもの、または length を持つものです。
→ 反復可能とイテレータ
console.log(Array.from({ length: 3 })); console.log(Array.from({ length: 3 }, (unused, i) => i * 2)); console.log(Array.from({ a: 1 }));
[ undefined, undefined, undefined ] [ 0, 2, 4 ] []
length が無いものは黙って空配列になります。エラーにはなりません。
new Array(3) は「穴」を作る
ここが最大の落とし穴です。
const holed = new Array(3);
console.log(holed);
console.log(holed.length);
console.log(holed.map((value, i) => i));[ <3 empty items> ] 3 [ <3 empty items> ]
length は3なのに、map() が1度も呼ばれません。
undefined が3つ入っているのではなく、要素が存在しない状態です。
map() / forEach() / filter() は、この穴を飛ばします。
Array.from() なら、ちゃんと undefined が入ります。
console.log(Array.from({ length: 3 })); console.log(Array.from({ length: 3 }).map((value, i) => i));
[ undefined, undefined, undefined ] [ 0, 1, 2 ]
fill() で埋めても直ります。
console.log(new Array(3).fill(0).map((value, i) => i));
[ 0, 1, 2 ]
引数が1つか2つかで意味が変わる
console.log(new Array(3));
console.log(new Array(1, 2, 3));[ <3 empty items> ] [ 1, 2, 3 ]
数値を1つ渡したときだけ「長さ」の意味になります。
これを避けるために Array.of() があります。
console.log(Array.of(3)); console.log(Array.of(1, 2, 3));
[ 3 ] [ 1, 2, 3 ]
Array.of() は必ず要素として扱います。
長さに使えない値を渡すと落ちます。
try { new Array(-1); } catch (error) { console.log(error.name + ': ' + error.message); }
RangeError: Invalid array length
→ RangeError: Invalid array length
fill() で同じものを共有してしまう
const grid = new Array(2).fill([]);
grid[0].push('x');
console.log(JSON.stringify(grid));[["x"],["x"]]
片方に足したのに、両方に入りました。
fill() は同じ1つのものを全部に置くからです。
毎回作りたいなら Array.from() の第2引数です。
const grid = Array.from({ length: 2 }, () => []); grid[0].push('x'); console.log(JSON.stringify(grid));
[["x"],[]]
オブジェクトや配列を fill() に渡さないでください。 数値や文字列なら問題ありません。
連番を作る
console.log(Array.from({ length: 5 }, (unused, i) => i)); console.log(Array.from({ length: 5 }, (unused, i) => i + 1)); console.log(Array.from({ length: 3 }, (unused, i) => i * 10));
[ 0, 1, 2, 3, 4 ] [ 1, 2, 3, 4, 5 ] [ 0, 10, 20 ]
これがいちばん短い書き方です。
for で push() しても同じですが、行数が増えます。
スプレッドとの使い分け
console.log([...'あい']); console.log([...new Set([1, 1, 2])]);
[ 'あ', 'い' ] [ 1, 2 ]
反復可能なものなら、[...x] のほうが短く書けます。
| 使うもの | 何ができるか |
|---|---|
[...x] |
反復可能なものだけ。いちばん短い |
Array.from(x) |
length だけのものも扱える。加工の関数を渡せる |
Array.of(a, b) |
渡した値をそのまま要素にする |
new Array(n) |
長さだけ決める。中身は穴 |
{ length: 3 } のような形は反復可能ではないので、
スプレッドでは開けません。
try {
console.log([...{ length: 3 }]);
} catch (error) {
console.log(error.name + ': ' + error.message);
}TypeError: {(intermediate value)} is not iterableまとめ
Array.from()は反復可能なものとlengthを持つものから作る。第2引数で加工できるnew Array(3)が作るのは穴。map()もforEach()も飛ばす- 数値1つを渡したときだけ「長さ」になる。避けたいなら
Array.of() fill()にオブジェクトや配列を渡すと、全部が同じものを指す- 連番は
Array.from({ length: n }, (unused, i) => i) - 反復可能なだけなら
[...x]が短い