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.