skip to Main Content

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


  1. Chosen as BEST ANSWER

    Thanks everyone, Im a dumbass, I was changing the array someone else in the code and was throwing this error. Sorry and thank you.


  2. let gameState = {
        grid: [],
        playing: false,
    };
    
    for (let i = 0; i < 3; i++) {
        // change to push here!
      gameState.grid.push([])
      for (let j = 0; j < 3; j++) {
        // change here
        const objectToPush = {
          state: 0,
          pos: {
            x: i * 3,
            y: j * 3,
          },
          color: {
            r: 0,
            g: 200,
            b: 0,
          },
        };
        // change to push here!
        gameState.grid[i].push(objectToPush);
      }
    }
    
    console.log("gameState is", gameState);
    console.log("gameState.grid[0][0] is", gameState.grid[0][0])
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search