javascript - Nested for-loop overwrites object attribute -
i broke down code simplified jsfiddle. problem attribute is
set 1 object in end every object gets value of last iteration (in case false
id05
should true
). why it? overlook something?
jsfiddle (see in console)
var reminder = { id0: { id: 0, medid: 0 } }; var chart = { id0: { medid: 0, values: [[5,1]] } } var tmp = {}; for(var = 0; < 10; i++) { (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];
copy reference object , not clone object itself.
consider this:
var = { a: [] }; var b = a.a; b.push(1); console.log(a.a); // [1]
this means objects same , share 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 can use object.create
make shallow clone (only clone top level properties)
Comments
Post a Comment