有人能解释一下为什么在这种情况下obj会返回{a:2}而不是{a:1}吗?
var obj = {a:1};
var data = {b:obj};
data.b.a = 2;
console.log(obj); // {a:2}发布于 2013-01-20 02:56:24
在这种情况下,您不是在克隆对象,而是设置对同一变量的额外引用。data.obj.a和obj.a指向完全相同的内存位置。第3行将该内存值设置为2。
要执行深度克隆,请尝试执行以下操作:
var data = JSON.parse(JSON.stringify(obj));发布于 2014-03-21 00:32:11
如果使用NS派生的浏览器,如FF:
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 ( ) } ;在文章中发表了很多很多的尝试,希望deepClone也能这么做
The structured clone algorithm - Web developer guide | MDN
提示:皇帝没穿衣服
https://stackoverflow.com/questions/14417645
复制相似问题