I'm trying to modify one value in a 2D array. However I'm finding some weird behavior based on how the array is constructed.
The only difference between matrix and matrix2 is how they're constructed. However when I change the [1][1] value, all of the [x][1] values in matrix2 are changed:
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);
Can anyone explain what's going on?
matrix2has three elements, each of which refers to the same array. Simple test:matrix2[0] === matrix2[1]results intrue.