我使用大小为 8 * 8 的数组类创建了一个数组,并使用 fill 用虚拟对象填充它。之后我创建了一个 for 并分配了值。但是当我打印数组时。所有字段都有相同的值。
var gridSize = 8;
const colorname = ["Red", "Orange", "Green", "Blue", "Purple", "Yellow"];
var gameGrid = new Array(gridSize * gridSize).fill({
loc: null,
color: null,
index: null,
value: null
});
fillTheGrid();
function fillTheGrid() {
for (var i = 0; i < gridSize * gridSize; i++) {
addElement(i)
}
}
// actual code Is big so im using I for index and value
function addElement(i){
gameGrid[i].loc = i;
let randomColor = Math.floor(Math.random() * colorname.length);
gameGrid[i].color = colorname[randomColor];
gameGrid[i].index = i;
gameGrid[i].value = i;
}
log(gameGrid);
预期输出是
[{"loc":1,"color":"Green","index":1,"value":1},{"loc":2,"color":"Red","index":2,"value":2},......,{"loc":63,"color":"Green","index":63,"value":63}]
但我得到了
[{"loc":63,"color":"Green","index":63,"value":63},...,{"loc":63,"color":"Green","index":63,"value":63}]
那就是我对所有人都获得相同的价值