Array.fill(Array) creates copies by references not by value
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); });