我有这段代码,但是每当我运行findTimeSlots()时,它都会立即弄乱我的全局数组apptData,但是在该函数的任何地方都看不到应该更改的地方。

(ConsoleLog)

(index):69
(4) [{…}, {…}, {…}, {…}]
0: {service: "A, B", duration: 50, tech: "C"}
1: {service: "B", duration: 30, tech: "C"}
2: {service: "A, D", duration: 60, tech: "A"}
3: {service: "D", duration: 40, tech: "A"}
length: 4
__proto__: Array(0)
(index):45
(4) [{…}, {…}, {…}, {…}]
0: {service: "A, B", duration: 50, tech: "C"}
1: {service: "B", duration: 30, tech: "C"}
2: {service: "A, D", duration: 60, tech: "A"}
3: {service: "D", duration: 40, tech: "A"}
length: 4
__proto__: Array(0)


///////////////////////////////////////////////////// ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// /

var apptData = [];
function addApptData(serviceName, rawDuration, selectedTech){
    apptData.push({
        'service': serviceName,
        'duration': rawDuration,
        'tech' : selectedTech
    })
}
function reduceApptData(index){
    apptData.splice(index, 1);
}
function findTimeSlots(dateStr){
    console.log(apptData);             //* Index 45 *//
    var final = new Array();
    var service, duration;
    for(var i = 0; i < apptData.length; i++){
        var duplicated = false;
        for(var j = 0; j < final.length; j++){
            if(final[j].tech == apptData[i].tech){
                service = ", "+apptData[i].service;
                final[j].service += service;
                duration = apptData[i].duration;
                final[j].duration += duration;
                duplicated = true;
                break;
            }
        }
        if(!duplicated){
            final.push(apptData[i]);
        }
    }
 }
addApptData("A", 20, "C");
addApptData("B", 30, "C");
addApptData("A", 20, "A");
addApptData("D", 40, "A");
console.log(apptData);                //* Index 69 *//
// If I remove the line below, I get the expected result, when I try to
// run with this line it will mess up apptData[]
findTimeSlots("");


我期望是

0: {service: "A", duration: 20, tech: "C"}
1: {service: "B", duration: 30, tech: "C"}
2: {service: "A", duration: 20, tech: "A"}
3: {service: "D", duration: 40, tech: "A"}
length: 4
__proto__: Array(0)


所以基本上我希望它保持不变。

我想将我的var apptData合并到我的findTimeSlots()中的var final中

调试后,我发现我的apptData由于某些原因而意外更改。

我怀疑这很琐碎,但我无法为自己的一生弄清楚。

最佳答案

这个小例子说明了发生了什么:

let a = {test: 10};
let b = a;
b.text = 11;
console.log(a); //this will print {test: 11}


由于a是对象,因此当您分配let b = a;时,实际上是在保存对a的引用,而不是克隆a

您需要克隆对象apptData[i],然后执行See this answer

因此,您应该推送克隆的final.push(apptData[i]);而不是apptData[i]

希望能有所帮助。

关于javascript - 与JSON混合的Javascript数组无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55527360/

10-12 14:10