When I try to create a new 2d array the first index is an empty array.
let gameState = {
grid: [],
playing: false,
};
for (let i = 0; i < 3; i++) {
gameState.grid[i] = [];
for (let j = 0; j < 3; j++) {
gameState.grid[i][j] = {
state: 0,
pos: {
x: i * 3,
y: j * 3,
},
color: {
r: 0,
g: 200,
b: 0,
},
};
}
}
Not sure where its mutating, the debugger shows it correctly but if i try to access the element its empty.
Tried used an Array(3).fill(…)
Output
gameState.grid = [
[],
[{object},{object},{object}],
[{object},{object},{object}],
]
Expected
gameState.grid = [
[{object},{object},{object}],
[{object},{object},{object}],
[{object},{object},{object}],
]
DevTools output
{
"grid": [
[],
[
{
"state": 0,
"pos": {
"x": 3,
"y": 0
},
"color": {
"r": 0,
"g": 200,
"b": 0
}
},
// rest of the object
],
"playing": false
}
2
Answers
Thanks everyone, Im a dumbass, I was changing the array someone else in the code and was throwing this error. Sorry and thank you.