var collection = { "5439": { "album": "ABBA Gold"
}
};function updateRecords(id, prop, value) {
collection1 = collection; document.write("begin "+JSON.stringify(collection)+"</br>");
collection1[id][prop]=value; document.write(JSON.stringify(collection1)+"</br>");
}
updateRecords(5439, "tracks", "Addicted to Love");
updateRecords(5439, "test", "my test");为何结果是begin {"5439":{"album":"ABBA Gold"}}"5439":{"album":"ABBA Gold","tracks":"Addicted to Love"}}
begin {"5439":{"album":"ABBA Gold","tracks":"Addicted to Love"}}
{"5439":{"album":"ABBA Gold","tracks":"Addicted to Love","test":"my test"}}不是begin {"5439":{"album":"ABBA Gold"}}
{"5439":{"album":"ABBA Gold","tracks":"Addicted to Love"}}
begin {"5439":{"album":"ABBA Gold"}}
{"5439":{"album":"ABBA Gold","test":"my test"}}collection是全局变量,我在函数里面也仅仅是对局部变量collection1赋值,collection1的改变,为何影响到了collection?
1 回答

翻翻过去那场雪
TA贡献2065条经验 获得超14个赞
浅拷贝,经常犯的错误。因为原始对象和新对象引用的同一个内存地址,因此改变一个值就会改变另一个的值。
解决办法:
var b = JSON.parse(JSON.stringify(a));// 当然全部会转成String,带有function之类的对象就会有问题
或
Object.freeze(a);// 建议这个,好像怎么玩都可用var b = a;
或jquery的extend,反正各种解决办法...
添加回答
举报
0/150
提交
取消