Array.fill(Array) creates copies by references not by value [duplicate]

 ̄綄美尐妖づ 提交于 2019-11-26 15:28:38

You could use Array.from() instead:

Thanks to Pranav C Balan in the comments for the suggestion on further improving this.

let m = Array.from({length: 6}, e => Array(12).fill(0));

m[0][0] = 1;
console.log(m[0][0]); // Expecting 1
console.log(m[0][1]); // Expecting 0
console.log(m[1][0]); // Expecting 0

Original Statement (Better optimized above):

let m = Array.from({length: 6}, e => Array.from({length: 12}, e => 0));

You can't do it with .fill(), but you can use .map():

let m = new Array(6).map(function() { return new Array(12); });

edit oh wait that won't work; .map() won't iterate through the uninitialized elements. You could fill it first:

let m = new Array(6).fill(null).map(function() { return new Array(12); });

You can't do it with Array#fill method. Instead iterate over the array and add newly created array using a for loop.

let m = Array(6);
for (var i = 0; i < m.length; i++)
  m[i] = Array(12).fill(0)

m[0][0] = 1;
console.log(m[1][0]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!