Javascript - 如何克隆对象? [英] Javascript - How to clone an object?
问题描述
我很困惑。我从 myObjOne
创建一个副本,而不是从 myObjOne
中删除一个条目,JS删除我的副本中的条目code> myObjTwo )?但为什么?
I am confused. I create a copy from myObjOne
, than i delete an entry from myObjOne
and JS delete the entry in my copy(myObjTwo
) too? But why?
myObjOne = {};
myObjOne['name'] = 'xxx';
myObjOne['id'] = 'yyy';
myObjOne['plz'] = 'zzz';
// clone
myObjTwo = myObjOne;
// remove something
delete myObjOne['name'];
console.dir(myObjTwo);
示例
http://jsbin.com/itixes/edit#javascript,html
推荐答案
更新:删除 Object.create
作为评论中指出的克隆方法。
Update: Removing Object.create
as a method of cloning as indicated in comments.
myObjTwo = myObjOne;
不克隆。它只是复制引用。
does not clone. It simply copies the reference.
如果您要克隆,可以使用 JSON.parse
和 JSON.stringify
If you want to clone, you can use JSON.parse
and JSON.stringify
var x = {a:{b:{c:{'d':'e'}}}};
var y = JSON.parse(JSON.stringify(x)); //y is a clone of x
console.log(y.a.b.c.d); //prints e
console.log(y === x); //prints false
警告: Raynos在评论中提到,基于类的克隆不会在输出对象中保留输入对象的方法。如果你的对象不包含任何方法,这个解决方案就足够了。方法是作为函数的对象的属性。 If var obj = {add:function(a,b){return a + b;}}
then add
is obj
的方法。
Warning: As Raynos mentioned in comments, this JSON based clone does not retain methods of the input object in the output object. This solution is good enough if your object does not contain any methods. Methods are properties of a object that are functions. If var obj = {add : function(a,b){return a+b;}}
then add
is a method of obj
.
如果您需要一个支持方法复制的解决方案, (由musefan,Matt和Ranhiru Cooray指出)
If you need a solution that supports copying of methods, then go through these SO answers (as pointed out by musefan, Matt and Ranhiru Cooray)
- Copying an Object in Javascript
- What is the most efficient way to clone a JavaScript object?
这篇关于Javascript - 如何克隆对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!