javascript - Objects empty after code refactoring -
i don't understand why following code produces different outputs:
first algorithm:
var data = { l1: 1, l2: 2, l3: 3 }; var datas = []; (var = 0; < 3; i++) { datas[i] = {} (key in data) { datas[i][key] = data[key] } }; delete datas[0].l1 delete datas[1].l2 delete datas[2].l3 console.log(data) console.log("%j", datas)
output:
{ l1: 1, l2: 2, l3: 3 } [{"l2":2,"l3":3},{"l1":1,"l3":3},{"l1":1,"l2":2}]
second algorithm:
var data = { l1: 1, l2: 2, l3: 3 }; var datas = []; (var = 0; < 3; i++) { datas[i] = {} datas[i] = data ; }; delete datas[0].l1 delete datas[1].l2 delete datas[2].l3 console.log(data) console.log("%j", datas)
output:
{} [{},{},{}]
following line second block/algo:
datas[i]=data
you defining reference same object data
(and not new objects). so, after delete properties data
object, references reflect change.
Comments
Post a Comment