javascript - 将对象推入数组的正确方法是什么?
问题描述
我一直在尝试不同的方法将简单的坐标作为对象添加{x:0, y:1}
到数组中,如果我手动添加它们,可以这么说。
但是如果我使用循环,结果会违背我的理解。生成的数组具有从循环内部推送的所有对象,其值与最后推送的对象完全相同。
function(){
var plot = ['south','east','north','east','north'] // user input
let records = [ // the array, with an initial object
{x: 0, y: 0}
];
var step ={ // object to modify and copy into array
x: 0,
y: 0,
};
for (var i = 0; i < plot.length; i++) {
if (plot[i] == "north"){
step.y++;
}
if (plot[i] == "east"){
step.x++;
}
if (plot[i] == "south"){
step.y--;
}
if (plot[i] == "west"){
step.x--;
}
console.log(step.x+','+step.y); // shows that the data is correctly modified
records.push(step);
console.log(records.length); // shows that the object was added to the array
}
for (var i = 0; i < records.length; i++) {
var newItem = records[i];
console.log('newItem: x='+newItem.x+' y='+newItem.y);
}
}
此外,在上面的示例中,数组的长度被认为是2
即使6
在循环执行期间明显达到的长度。
我不知道是逻辑错误,还是我的电脑在欺骗我。
解决方案
您需要在循环step
内初始化:for
var plot = ['south', 'east', 'north', 'east', 'north'] // user input
let records = [ // the array, with an initial object
{ x: 0, y: 0 }
];
for (var i = 0; i < plot.length; i++) {
var step = { // object to modify and copy into array
x: i > 0 ? records[i-1].x : 0,
y: i > 0 ? records[i-1].y : 0,
};
if (plot[i] == "north") {
step.y++;
}
if (plot[i] == "east") {
step.x++;
}
if (plot[i] == "south") {
step.y--;
}
if (plot[i] == "west") {
step.x--;
}
console.log(step.x + ',' + step.y); // shows that the data is correctly modified
records.push(step);
console.log(records.length); // shows that the object was added to the array
}
console.log(records);
推荐阅读
- kotlin - 如何重写这种“检查、分配和返回”模式?
- c# - 服务器端数据注释不适用于 DateTime 数组类型
- databricks - Azure 事件中心到 Databricks,正在使用的数据帧会发生什么情况
- php - 登录功能无效
- java - 获取当前文件的目录
- c# - 在 Binder 托管的 Jupyter 上设置 C# 和 F# 笔记本
- c - 斐波那契的 OpenMP 并行程序比顺序程序慢
- c# - Wix Installer 应用程序在运行两次并卸载应用程序时不会安装
- excel - VBA将单元格位置复制到另一个工作表中找到的单元格
- css - Bootstrap-Vue中如何增加tooltip的宽度