Javascript Multidimensional Array complete column getting set

Viewed 60

I am trying to make a game in Javascript. The game board is intialized to a zero-filled 2-D array. However, when I am setting the value of a single point, the complete column is getting set with that value. I think this is some issue with the way I am initializing the Array.

Method 1

# initialization
gameState = Array(6).fill(Array(7).fill(0))

# later in the game
gameState[2][4] = 1

# results in complete 4th index column to be assigned the value 1, like so -
0: (7) [0, 0, 0, 0, 1, 0, 0]
1: (7) [0, 0, 0, 0, 1, 0, 0]
2: (7) [0, 0, 0, 0, 1, 0, 0]
3: (7) [0, 0, 0, 0, 1, 0, 0]
4: (7) [0, 0, 0, 0, 1, 0, 0]
5: (7) [0, 0, 0, 0, 1, 0, 0]

Method 2

# initialization
let gameState = [];
for (let i=0; i<MAX_ROWS; i++) {
    let row = []
    for (let j=0; j<MAX_COLUMNS; j++) {
       row.push(0)
    }
    gameState.push(row);
}

# again similar assignment
gameState[2][4] = 1

# results in correct state of the array
0: (7) [0, 0, 0, 0, 0, 0, 0]
1: (7) [0, 0, 0, 0, 0, 0, 0]
2: (7) [0, 0, 0, 0, 1, 0, 0]
3: (7) [0, 0, 0, 0, 0, 0, 0]
4: (7) [0, 0, 0, 0, 0, 0, 0]
5: (7) [0, 0, 0, 0, 0, 0, 0]

Can someone please explain what I am doing wrong here?

1 Answers

Your problem is pretty simple.

Array(6).fill(Array(7).fill(0))

Let's explain what this does.

Array(6)

creates a holey array with space for 6 items.

.fill(...)

will fill up these 6 holes with what ever you put in as argument.

Now comes the issue..

In Javascript, the arguments are evaluated before the execution of the function is run.

This means (in this exact case where .fill(...) is only ran once) your code is exactly the same as:

const innerArray = [0,0,0,0,0,0,0];
gameState = Array(6).fill(innerArray);

This means it fills the outer array with exactly the same array instance 6 times.

What you want is to create separate arrays each time. Just do this instead:

gameState = [...Array(6)].map(() => [...Array(7)].map(() => 0))
Related