全局变量的值为何被改变了?

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?


Smart猫小萌
浏览 1034回答 1
1回答

翻翻过去那场雪

浅拷贝,经常犯的错误。因为原始对象和新对象引用的同一个内存地址,因此改变一个值就会改变另一个的值。解决办法:var&nbsp;b&nbsp;=&nbsp;JSON.parse(JSON.stringify(a));//&nbsp;当然全部会转成String,带有function之类的对象就会有问题或Object.freeze(a);//&nbsp;建议这个,好像怎么玩都可用var&nbsp;b&nbsp;=&nbsp;a;或jquery的extend,反正各种解决办法...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript