谁能解释为什么obj
退货{a:2}
而不是{a:1}
在这种情况下?
var obj = {a:1};
var data = {b:obj};
data.b.a = 2;
console.log(obj); // {a:2}
谁能解释为什么obj
退货{a:2}
而不是{a:1}
在这种情况下?
var obj = {a:1};
var data = {b:obj};
data.b.a = 2;
console.log(obj); // {a:2}
javascript 中的对象是通过引用的,因此当您更改一个引用时,您就更改了它们。这个的意思是你刚刚创建了一个浅拷贝,你需要做一个深克隆。
可以通过这种方式使用 jQuery 进行深度复制:
// Deep copy
var newObject = jQuery.extend(true, {}, obj);
阅读我使用 jQuery 的原因:
在 JavaScript 中深度克隆对象的最有效方法是什么?
(这是 Stackoverflow 上的 John Resig ......)
如果使用像 FF 这样的 NS 派生浏览器:
var data = { b: eval ( obj . toSource ( ) ) } ;
或者
var data = { b: eval ( uneval ( obj ) ) } ;
如果不:
Object . function . deepClone = function(){
/*
highly non-trivial to accommodate objects like:
animal=123; animal.beastly=432; ie. object "overloading"
monster = new ( function ( ) { this . this = this } ) ( ) ie. self-referential / recursive
Note: JSON cannot do these but toSource () can handle recursive structures
alert ( new ( function ( ) { this . this = this } ) ( ) . toSource ( ) );
ie. #1={this:#1#}
alert ( new ( function ( ) { this [ this ] = this } ) ( ) . toSource ( ) );
ie. #1={'[object Object]':#1#}
alert ( new ( function ( ) { this [ this . toSource ( ) ] = this } ) ( ) . toSource ( ) );
ie. #1={'({})':#1#}
alert ( ( #1 = { '({})' : #1# } ) . toSource ( ) );
ie. #1={'({})':#1#}
*/
}
var data = { b: obj . deepClone ( ) } ;
在 SO 中发布了很多很多尝试进行 deepClone 以及
结构化克隆算法 - Web 开发人员指南 | MDN
提示:皇帝没有衣服
In this case you're not cloning objects but rather setting additional references to the same variable. data.obj.a and obj.a point to the exact same memory location. Line 3 sets this memory value to 2.
To do a deep clone, try this:
var data = JSON.parse(JSON.stringify(obj));