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?
浅拷贝,经常犯的错误。因为原始对象和新对象引用的同一个内存地址,因此改变一个值就会改变另一个的值。
解决办法:
或
或jquery的extend,反正各种解决办法...