首页 > 解决方案 > 将对象推入数组的正确方法是什么?

问题描述

我一直在尝试不同的方法将简单的坐标作为对象添加{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在循环执行期间明显达到的长度。

我不知道是逻辑错误,还是我的电脑在欺骗我。

标签: javascriptarraysobject

解决方案


您需要在循环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);

推荐阅读