I\'ve ran into an issue with the new Array.prototype.fill
method due to unexpected output when using it with Array.prototype.map
. For example:
Your code is equivalent to:
let inner = Array(3).fill(0);
let M = Array(3).fill(inner);
When you pass inner
to .fill()
, it doesn't make copies of it, the M
array contains 3 references to the same array. So anything you do to one element of M
happens to them all.
You need to make new arrays for each element of M
:
let M = [];
for (var i = 0; i < 3; i++) {
M.push(Array(3).fill(0));
}