javascript中的重复对象 [英] Duplicate object in javascript
问题描述
我看到两种复制对象的方法
I see two ways to duplicate objects
1.
var a={c:1}
var b=a;
alert(b.c);//alert 1
2。
var a={c:2};
var b={};
for (i in a)
{b[i]=a[i];}
alert(b.c);//alert 1
第一个比第二个短,那么第二个例子的效率是多少?
The first are shorter than the second so what is the efficiency in the second example?
推荐答案
第一个不创建副本,只是复制引用,所以 a
和 b
在操作后指向同一个对象。
The first does not create a copy, but just copies the reference, so a
and b
point towards the same object after the operation.
然而,在第二种情况下,每个属性都是单独复制的,因此创建了一个真实的副本。 a
中的对象(只要属性中只有原始类型,否则你会在更深层次上遇到同样的问题)。
In the second case, however, each attribute is copied separately, thus creating a "real" copy of the object in a
(as long as there are just primitive types in the properties, else you got the same problem at a deeper level).
所以在第一种情况下如果你改变 bc
那么 ac
也会改变,而在第二种情况不会。
So in the first case if you change b.c
then a.c
will also change, while in the second case it wont.
这篇关于javascript中的重复对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!