JavaScript 多次元配列の初期化

多次元配列の初期化

const a = Array(3).fill(null);
const ma = a.map(a => a = Array(2).fill('hoge'));

console.log(ma);
// [["hoge", "hoge"], ["hoge", "hoge"], ["hoge", "hoge"]]

mapを使うとコンパクトにできる。

注意

const a = Array(3); //← .fill(null)を消すと
const ma = a.map(a => a = Array(2).fill('hoge'));

console.log(ma);
// Error: Cannot read property 'constructor' of undefined

.fill()を忘れると怒られる。