0

I am seeing weird behavior when trying to modify a 2-dimensional array that represents a tic-tac-toe board. The first element of all the arrays are modified instead of the one.

// BEFORE: squares = [[null,null,null],[null,null,null],[null,null,null]]
squares[0][0] = 'X';
// AFTER: squares = [["X",null,null],["X",null,null],["X",null,null]]

I was able to fix the issue with the following code, but I am curious as to why this happens. Here is the working code:

let rowToModify = squares[yCoord].slice();
rowToModify[xCoord] = 'X';
squares[yCoord] = rowToModify;
2
  • Works just fine - jsfiddle.net/abhitalks/51110618 Commented May 4, 2017 at 6:00
  • Doing squares[0][0] = 'X'; now way it can modify all the first elements. You might be doing something wrong. Commented May 4, 2017 at 6:01

2 Answers 2

4

You are likely initializing squares by using the same array three times. Something like this:

row = [null, null, null];
squares = [row, row, row];

However since row is all the same array, when you modify it, it will modify in all rows.

If you do:

squares = [[null,null,null], [null,null,null], [null,null,null]];

You will not get the problem.

The reason the other code works is because slice creates a new list, so you are no longer referencing the original list. Therefore it may be modified separately.

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

Comments

1

Try like this squares.map(a => a[0]='x') using Array#map

var squares = [
  [null, null, null],
  [null, null, null],
  [null, null, null]
]
squares.map(a => a[0]='x')
console.log(squares)

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.