-1

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?

1
  • 2
    matrix2 has three elements, each of which refers to the same array. Simple test: matrix2[0] === matrix2[1] results in true. Commented Aug 13, 2013 at 21:14

1 Answer 1

2
[row, row, row]

You just made an array with three references to the same inner array.

Changes to the inner array can be seen through any reference to it.

You want to create three copies of the inner array.
You can create a shallow copy of an array by calling .slice().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.