首页 > 解决方案 > 我使用 for 为数组赋值,但是当我打印数组时,它只是在整个数组中的最后一个值

问题描述

我使用大小为 8 * 8 的数组类创建了一个数组,并使用 fill 用虚拟对象填充它。之后我创建了一个 for 并分配了 values 。但是当我打印数组时。所有字段都有相同的值。

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}]

那就是我为所有人获得相同的价值

标签: javascriptarraysobject

解决方案


在 JS 中对象是通过引用传递的,所以当你这样做时

var gameGrid = new Array(gridSize * gridSize).fill({
    loc: null,
    color: null,
    index: null,
    value: null
});

每个位置都放置相同的对象 - 如果您更新其中任何一个,则更新“全部”。您需要做的是通过执行以下操作在每个位置放置一个不同的对象:

var gameGrid = new Array(gridSize * gridSize).fill(null).map(i => ({
    loc: null,
    color: null,
    index: null,
    value: null
});

var gridSize = 8;
    const colorname = ["Red", "Orange", "Green", "Blue", "Purple", "Yellow"];

var gameGrid = new Array(gridSize * gridSize).fill(null).map(i => ({
        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;
}

console.log(gameGrid);


推荐阅读