Javascript - 如何克隆一个对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7965822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - How to clone an object?
提问by user970727
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
并且 JS 也删除了我的副本(myObjTwo
)中的条目?但为什么?
myObjOne = {};
myObjOne['name'] = 'xxx';
myObjOne['id'] = 'yyy';
myObjOne['plz'] = 'zzz';
// clone
myObjTwo = myObjOne;
// remove something
delete myObjOne['name'];
console.dir(myObjTwo);
回答by Narendra Yadala
Update: Removing Object.create
as a method of cloning as indicated in comments.
更新:删除Object.create
作为评论中指出的克隆方法。
myObjTwo = myObjOne;
does not clone. It simply copies the reference.
不克隆。它只是复制引用。
If you want to clone, you can use JSON.parse
and JSON.stringify
如果你想克隆,你可以使用JSON.parse
和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
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
.
警告:正如 Raynos 在评论中提到的,这个基于 JSON 的克隆不会在输出对象中保留输入对象的方法。如果您的对象不包含任何方法,此解决方案就足够了。方法是作为函数的对象的属性。如果var obj = {add : function(a,b){return a+b;}}
thenadd
是 的方法obj
。
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)
如果您需要支持方法复制的解决方案,请查看这些 SO 答案(如 musefan、Matt 和 Ranhiru Cooray 所指出的)
- How do I correctly clone a JavaScript object?
- What is the most efficient way to deep clone an object in JavaScript?
I would suggest How do I correctly clone a JavaScript object?
回答by Nicu Surdu
You can use jQuery like so:
你可以像这样使用jQuery:
var myObjTwo = jQuery.extend(true, {}, myObjOne);
The first argument indicates that we want to make a deep copy of myObjOne
.
第一个参数表明我们想要制作myObjOne
.
回答by musefan
That is not how you clone, that is simply storing the same original object in an extra variable. Maybe this answerwill help you
这不是您克隆的方式,它只是将相同的原始对象存储在一个额外的变量中。也许这个答案会帮助你
回答by RobG
Lots of advice on how to make a copy not only of the object and it's properties, but of all the objects referenced by its properties. Here's a version that clones the object without copying it and so that the clone inherits all properties added later except for those shadowed by own properties of the clone:
关于如何不仅复制对象及其属性,而且复制由其属性引用的所有对象的大量建议。这是一个克隆对象而不复制它的版本,以便克隆继承以后添加的所有属性,除了那些被克隆的自己的属性遮蔽的属性:
var cloneOf = (function() {
function F(){}
return function(o) {
F.prototype = o;
return new F();
}
}());
Some may recognise the pattern. An example:
有些人可能会认出这种模式。一个例子:
var base = {foo:'foo', bar:'bar'};
var baseClone = cloneOf(base);
alert(baseClone.foo); // foo
回答by Pablo
You can use Object.assign()
but be aware of browser support.
您可以使用,Object.assign()
但要注意浏览器支持。
More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign.
更多信息:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign。
Example:
例子:
myObjTwo = Object.assign({}, myObjOne);
回答by Allan Mwesigwa
With ES6, use the spread operator.
在 ES6 中,使用展开运算符。
myObjTwo = {...myObjOne}
The spread operator in es6 is just an ellipsis. It creates a copy of the original, even if the original is destroyed
es6 中的扩展运算符只是一个省略号。它会创建原件的副本,即使原件已被销毁
回答by Dinesh
Simple.
简单的。
var clone=function(o){
var n= {}.toString.apply(o)=="[object Array]" ? []:{};
for(i in o)
n[i]= typeof o[i]=='object' ? clone(o[i]):o[i];
return n;
};
Usage:
用法:
var x={a:{d:34},b:33};
var y=clone(x); // clones 'x'
回答by funkybro
Your line myObjTwo = myObjOne
does not clone myObjOne
, it just creates a duplicate reference to the same object!
您的行myObjTwo = myObjOne
不会 clone myObjOne
,它只是创建对同一对象的重复引用!
The actual answer is to use a clone function, perhaps from a library such as underscore.js. But really, it looks like you have some reading and learning to do about the concept of objects and pointers in Javascript.
实际的答案是使用克隆函数,可能来自诸如underscore.js 之类的库。但实际上,您似乎对 Javascript 中的对象和指针的概念有一些阅读和学习经验。