Why does this happen? I am trying to create a 2D array with an integer sequence. I know the alternate way to achieve the result, want to know the reason behind this behaviour.
Also, using new Array(3)
to fill the array shouldn't have caused any reference errors.
let length = 3
let arrMatrix = (new Array(3)).fill(Array(3));
arrMatrix.fill((new Array(3)).fill(0));
var sum = 0;
for(let i=0; i<length; i++) {
for(let j=0; j<length; j++) {
arrMatrix[i][j] = sum;
sum += 1;
}
}
console.log(arrMatrix);
Output
[ [ 6, 7, 8 ], [ 6, 7, 8 ], [ 6, 7, 8 ] ]
Expected output
[ [ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ] ]