简体   繁体   中英

Nested for-loop overwrites object attribute

I broke down my code to a simplified jsFiddle. The problem is that the attribute is is only set for one object but in the end every object gets the value of the last iteration (in this case it is false but id05 should be true ). Why is it? Do I overlook something?

jsFiddle (see in the console)

var reminder = {
    id0: {
        id: 0,
        medId: 0
    }
};

var chart = {
    id0: {
        medId: 0,
        values: [[5,1]]
    }
}
var tmp = {};

for(var i = 0; i < 10; i++) {
    for (id in reminder) {
        tmp[id + i] = reminder[id];
        tmp[id + i].is = false;

        for(var j = 0; j < chart["id" + reminder[id].medId].values.length; j++) {
            if (chart["id" + reminder[id].medId].values[j][0] === i) {
                tmp[id + i].is = true;
            }
        }
    }
}

tmp[id + i] = reminder[id]; will copy the reference to the object and not clone the object itself.

Consider this:

var a = { a: [] }; 
var b = a.a; 
b.push(1);
console.log(a.a); // [1]

This means that all your objects are the same and they share the same properties ( tmp.id05 === tmp.id06 etc...)

tmp.id00.__my_secret_value__ = 1234;
console.log(tmp.id09.__my_secret_value__); // 1234

To clone objects in JavaScript you can use Object.create but this will only make a shallow clone (only clone top level properties)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM