[英]Javascript - How to clone an object?
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?我创建一个副本
myObjOne
,比我删除的条目myObjOne
和JS删除我的副本(入门myObjTwo
)吗? But why?但为什么?
myObjOne = {};
myObjOne['name'] = 'xxx';
myObjOne['id'] = 'yyy';
myObjOne['plz'] = 'zzz';
// clone
myObjTwo = myObjOne;
// remove something
delete myObjOne['name'];
console.dir(myObjTwo);
example http://jsbin.com/itixes/edit#javascript,html示例http://jsbin.com/itixes/edit#javascript,html
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.警告:正如 Raynos 在评论中提到的,这个基于 JSON 的克隆不会在输出对象中保留输入对象的方法。 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
.如果
var obj = {add : function(a,b){return a+b;}}
那么add
是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 所指出的)
I would suggest How do I correctly clone a JavaScript object?我建议如何正确克隆 JavaScript 对象?
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
的深层副本。
That is not how you clone, that is simply storing the same original object in an extra variable.这不是您克隆的方式,它只是将相同的原始对象存储在一个额外的变量中。 Maybe this answer will help you
也许这个答案会帮助你
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
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);
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'
With ES6, use the spread operator.在 ES6 中,使用展开运算符。
myObjTwo = {...myObjOne}
The spread operator in es6 is just an ellipsis. es6 中的扩展运算符只是一个省略号。 It creates a copy of the original, even if the original is destroyed
它会创建原件的副本,即使原件已被销毁
Your line myObjTwo = myObjOne
does not clone myObjOne
, it just creates a duplicate reference to the same object!您的行
myObjTwo = myObjOne
不会克隆myObjOne
,它只是创建对同一对象的重复引用!
The actual answer is to use a clone function, perhaps from a library such as underscore.js .实际的答案是使用克隆函数,可能来自诸如underscore.js 之类的库。 But really, it looks like you have some reading and learning to do about the concept of objects and pointers in Javascript.
但实际上,您似乎对 Javascript 中的对象和指针的概念有一些阅读和学习经验。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.