0

I'm going to write a tiny game, which need a two-dimensional array to store data,

    for (let i = 0; i < rowNum; i++) {
        snakeRow.push(new Array(rowNum).fill({ isWall: false, isSnake: false, orient: 0 }));
        for (let j = 0; j < rowNum; j++) {
            let temprow = document.createElement("li");
            temprow.setAttribute("x", j);
            temprow.setAttribute("y", i);
            if (i === 0 || i === rowNum - 1 || j === 0 || j === rowNum - 1) {
                temprow.style.backgroundColor = 'black';
                snakeRow[i][j].isWall = true;
            }
            playground.appendChild(temprow);
        }
    }

when i console.log(snakeRow) i found all the isWall is true. it seems like it fill the array with the same reference of my object and mdn confirms my guess.

// Objects by reference.
var arr = Array(3).fill({}) // [{}, {}, {}];
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]

but why fill() work like that. I don't think an array filled with the same thing work like a array, but only a singleton instance.

And is there anyway better than using for loop to push the object into my array? Thanks.

Loic
  • 160
  • 2
  • 13
  • If you have 2 for loops anyway, I'd push empty array to `snakeRow` and move that object to inner loop (like `let obj={/*props*/}; /*current inner loop body with replaced snakeRow[i][j] to obj*/ snakeRow[i].push(obj)`) – barbsan Oct 08 '18 at 09:43
  • `Array(3).fill().map(Object)` or `[...Array(3)].map(Object)` – Slai Oct 08 '18 at 10:00

0 Answers0