【问题标题】:Add new object to array将新对象添加到数组
【发布时间】:2016-01-14 12:23:26
【问题描述】:

我正在努力将新对象推送到数组中。目前,下面的代码似乎只是覆盖了一个对象。我可以通过控制台看到要推送到数组的数据,但它只是不存储新对象。有什么想法吗?

fs.readFile('check.json', function (err, check) {
    if (err) throw err;
    var newData = JSON.parse(check);

    var tempData =[];
    for (var index=0; index<newData.length; index++){
        tempData.push(newData);
        }
    tempData = newData;
});

【问题讨论】:

  • 您将最后一个元素分配给最后的数组吗? tempData = newData;
  • 您正在覆盖tempData 数组,方法是在最后一行使用newData 对其进行分配

标签: javascript arrays node.js object fs


【解决方案1】:

迭代数组然后将对象推送给它们的典型方法是这样的

var tempData =[];
for (var index=0; index<newData.length; index++){
    tempData.push(newData[index]);
    //                     ^add index
}
//tempData = newData; remove assignment which overwrites array

【讨论】:

  • 谢谢。您能否提供有关如何使用 fs 进行外部推动的任何见解?外部 json 以未定义的形式返回。特拉维斯 J
猜你喜欢
  • 2022-01-16
  • 2019-01-29
  • 2017-07-12
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 2018-09-06
  • 2019-10-29
  • 1970-01-01
相关资源
最近更新 更多