将新对象推送到数组,最后一个对象覆盖整个数组

时间:2018-02-14 03:25:08

标签: javascript node.js

我尝试在循环中推送一些对象,前三个是好的,但是当它想要推送最后一个时,整个数组将被最后一个对象覆盖!

让我说我有这个代码,在我的任务中,我有4个项目,其中3个有"type1"类型,其中只有一个有"type2",基本上第二个如果只触发一次,但由于某种原因,最后myArray填补了最后一次推动! :

var myArray = [];
for(var i = tasks.length-1; i>=0; i--){
   if (tasks[i].type == 'type1') {
     myObject.type= 'audio',
     myObject.command = audioArgs;
     myArray.push(myObject);
   } 
   if (tasks[i].type == 'type2') {
     console.log("Before push type2: ", myArray) // Here I will get the currect value
     myObject.type= 'video',
     myObject.command = videoArgs;
     myArray.push(myObject);
     console.log("After push type2 : ", myArray) // Here all old value which have type1 will overwrite with type2
   }
}

我将myObject定义为:

var myObject = {
  type : String,
  command : String
}

3 个答案:

答案 0 :(得分:1)

您需要在if块中声明myObject。目前在您的代码中,您将两次推送相同的引用,因此通过任何引用更新数据会更新另一个引用。正确的代码是:

var myArray = [];
for (var i = tasks.length - 1; i >= 0; i--) {
    if (tasks[i].type == 'type1') {
        let myObject = {
            type: 'audio',
            command: audioArgs
        }; //HERE
        myArray.push(myObject);
    }
    if (tasks[i].type == 'type2') {
        console.log("Before push type2: ", myArray);
        let myObject = {
            type: 'video',
            command: videoArgs
        }; //HERE

        myArray.push(myObject);
        console.log("After push type2 : ", myArray);
    }
}

答案 1 :(得分:1)

只需在for循环中包含此部分

即可
var myObject = {
  type : String,
  command : String
}

确保在每次迭代时初始化一个新对象。否则,您将覆盖同一个对象并多次推送,最终会得到一个包含对单个对象的多个引用的数组

答案 2 :(得分:1)

正如评论中指出的那样,您对要推入阵列的所有对象使用相同的引用。那么在这种情况下发生的是你的数组包含每n次迭代推送的项目。即第一推包含第一项。第2项包含2项,这两项都是已推入数组的第2项。因此,您需要一个本地范围。

var myArray = [];
for(var i = tasks.length-1; i>=0; i--){
   var myObject = {
     type : String,
     command : String
   }
   if (tasks[i].type == 'type1') {
     myObject.type= 'audio',
     myObject.command = audioArgs;
     myArray.push(myObject);
   } 
   if (tasks[i].type == 'type2') {
     console.log("Before push type2: ", myArray) // Here I will get the currect value
     myObject.type= 'video',
     myObject.command = videoArgs;
     myArray.push(myObject);
     console.log("After push type2 : ", myArray) // Here all old value which have type1 will overwrite with type2
   }
}
相关问题