0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptで空の多次元配列を new Array(n) で作成する

Posted at

結論

const n = 4;
const arr1 = new Array(n).fill(null).map(_ => []);

理由 

fill の中身にオブジェクトを放り込むと、シャローコピーで反映されるため

const n = 4;
const arr1 = new Array(n).fill([]);

arr1[0][0] = 1;
// [[1], [1], [1], [1]]
console.log(arr1);

これは仕様としてキチンと記載されている

// 配列の各スロットから参照される、単一のオブジェクト。
const arr = Array(3).fill({}); // [{}, {}, {}]
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]

なお、fill をすっとばすと意図しない動作になる
良い書き方が思いつかなかったのでこれで妥協

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?