I am facing an issue while trying to update a single value in a 2D array. The problem seems to be related to the way the array is initialized.
The peculiar behavior occurs when I make changes to the [1][1] value in matrix while leaving matrix2 unchanged:
Matrix:
[ [ 0, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 0 ] ]
Matrix2 (unexpected):
[ [ 0, 1, 0 ], [ 0, 1, 0 ], [ 0, 1, 0 ] ]
Code:
var row = [0,0,0];
var matrix = [[0,0,0],[0,0,0],[0,0,0]];
var matrix2 = [row, row, row];
console.log(matrix);
console.log(matrix2);
matrix[1][1] = 1;
matrix2[1][1] = 1;
console.log(matrix);
console.log(matrix2);
Would appreciate insights on this puzzling situation.