javascript - 我使用 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}]
那就是我为所有人获得相同的价值
解决方案
在 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);
推荐阅读
- c# - 我需要通过滑块改变对象的透明度
- javascript - Javascript/GAS-如何在 POST 请求中循环访问日期
- google-apps-script - 我可以增加对我的 Google Apps 脚本函数的内存分配以修复 502 服务器错误吗?
- reactjs - 用于创建 ReactJS 前端的方法或模式是什么,它或多或少是一系列您可以打开/关闭的组件
- javascript - react-native-testing-library 和 styled-components 无法访问道具
- r - ggplot:分组和绘制多条线,但分别处理它们
- bash - 如何通过apache气流运行shell脚本
- sum - 如何获取特定列中的特定行到 SUM?
- python - 转换日期格式:2 位年份到 4 位年份
- .net - .NET Core(所有版本)中的 REST API 调用失败,在 .NET 框架中工作