对于Javascript中循环追加对象多次

时间:2017-10-29 03:08:14

标签: javascript for-loop

我有以下代码。

const timeLabels = [
    { name: "1:00 AM", present: true, label: ["1:00", "2:00"], value: "1:00" },
    { name: "2:00 AM", present: true, label: ["2:00", "3:00"], value: "2:00"},
    { name: "3:00 AM", present: true, label: ["3:00", "4:00"], value: "3:00" },
];

const targetedTimes = [["0:00", "1:00"], ["1:00", "2:00"]]
  
    let actualTime = [];

    console.log("getting time");
    console.log("start: the actualTime is", actualTime);
    for (var j = 0; j < timeLabels.length; j++) {
        console.log("x");
        var currItem = timeLabels[j];
        var label = JSON.stringify(currItem.label);
        var adTime = JSON.stringify(targetedTimes);
        if (adTime.indexOf(label) >= 0) {
            currItem.present = true;
        } else {
            currItem.present = false;
        }
        console.log("the current item is", currItem);
        actualTime.push(currItem);
        console.log("The actual time is", actualTime);
    }

在FIRST迭代中,currItem是

{name: "1:00 AM", present: true, label: Array(2), value: "1:00"} 

但是实际时间是

   [{name: "1:00 AM", present: true, label: Array(2), value: "1:00"}, 
   {name: "2:00 AM", present: false, label: Array(2), value: "2:00"},
   {name: "3:00 AM", present: false, label: Array(2), value: "3:00"}]

当我在第一次迭代中只追加1时,为什么actualTime列表有三个值?

1 个答案:

答案 0 :(得分:1)

正在发生的事情是控制台正在打印对象的引用(因为数组是javascript中的一种对象),所以当你打印它并在控制台中读取它时,每个console.log语句都指向在同一个最终数组中,这就是每次值相同的原因。

Have a look at this similar StackOverflow question for more insight.

我尝试在节点上运行你的脚本并在每次迭代时正确地打印出数组,在第一次迭代中只有一个项目,所以你的代码很好。