【发布时间】:2021-03-05 09:48:23
【问题描述】:
我正在使用 Array() 构造函数创建一个大小为 3 的空数组,然后使用 forEach() 或 Array.fill() 填充它,但是当我尝试更改/改变数组中的任何元素时,任何类似的值另一个数组中的成员设置为分配给任何其他成员的最后一个值。 创建方法:
const createBoard = () => {
let row = Array(3);
const cellDS = {
isClcicked: false,
toPlayer: null,
cellID: null,
};
row.fill(cellDS);
let gameBoard = Array(3);
gameBoard.fill(row);
console.log("board created");
return gameBoard;
};
当我更改第一行第一个元素的单元格 ID 时,我得到以下结果:
[[
{ isClicked: false, toPlayer: null, cellID: 1 },
{ isClicked: false, toPlayer: null, cellID: 1 },
{ isClicked: false, toPlayer: null, cellID: 1 },
],
[
{ isClicked: false, toPlayer: null, cellID: 1 },
{ isClicked: false, toPlayer: null, cellID: 1 },
{ isClicked: false, toPlayer: null, cellID: 1 },
],
[
{ isClicked: false, toPlayer: null, cellID: 1 },
{ isClicked: false, toPlayer: null, cellID: 1 },
{ isClicked: false, toPlayer: null, cellID: 1 },
]]
isClicked 和 toPlayer 也是如此。
Vuex 代码:
const state = { gameBoard: [] };
const getters = {
getGameBoard: (state) => state.gameBoard,
};
const actions = {
createBoard: ({ commit }) => {
commit("setBoard");
},
editBoard: ({ commit }) => {
commit("changeBoard");
},
};
const mutations = {
setBoard: (state) => {
state.gameBoard = createBoard();
},
changeBoard: (state) => {
console.log("Before: " + state.gameBoard[0][0]["cellID"]);
state.gameBoard[0][0]["cellID"] = 1;
console.log("After: " + state.gameBoard[0][0]["cellID"]);
console.log("After: " + state.gameBoard[0][1]["cellID"]);
},
}
解决方案: fill() 在整个应用程序中创建元素的精确静态副本,您不能简单地在空数组上使用 forEach,例如 Array(3) 将返回 [ , , ] ,这本身是没有意义的(不确定的)。 所以你可以用空值填充它,然后在它上面使用 forEach()。
【问题讨论】:
-
你不能简单地在 [ , , ] 上使用 forEach