JavaScript 数组的浅拷贝和深拷贝有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24512712/
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
What is the difference between a shallow copy and a deep copy with JavaScript arrays?
提问by Niet the Dark Absol
According the MDN documentation calling array.slice()
will create a shallow copy of the array.
根据 MDN 文档调用array.slice()
将创建数组的浅拷贝。
See this MDN link for slice().
However, if I run a simple test as such in the console:
但是,如果我在控制台中运行一个简单的测试:
var test = [[1,2,3],7,8,9];
var shallow_copy = test.slice();
and inspect shallow_copy, I can see that the entire 2 dimensional array appears to be copied over.
并检查shallow_copy,我可以看到整个二维数组似乎被复制了。
What is the difference between a shallow copy and a deep copy? If I were to guess, I would have called this a deep copy.
浅拷贝和深拷贝有什么区别?如果我猜的话,我会称其为深拷贝。
回答by Niet the Dark Absol
To see the difference, try:
要查看差异,请尝试:
shallow_copy[0][2] = 4;
console.dir(test);
You'll see that test
has been modified! This is because while you may have copied the values to the new array, the nested array is still the same one.
你会看到test
已经修改了!这是因为虽然您可能已将值复制到新数组中,但嵌套数组仍然是相同的。
A deep copy would recursively perform shallow copies until everything is a new copy of the original.
深拷贝将递归地执行浅拷贝,直到所有内容都是原始副本的新副本。
回答by Rutwick Gangurde
Basically you're just getting a reference to the original variable/array. Changing the reference will also change the original array. You need to loop over the values of the original array and form a copy.
基本上,您只是获得对原始变量/数组的引用。更改引用也会更改原始数组。您需要遍历原始数组的值并形成副本。
Consider this example:
考虑这个例子:
var orig = { a: 'A', b: 'B', c: 'C' };
Let's say you want to create a duplicate of this, so that even if you change the original values, you can always return to the original.
假设您要创建此副本的副本,以便即使更改原始值,也始终可以返回到原始值。
I can do this:
我可以做这个:
var dup = orig; //Shallow copy!
If we change a value:
如果我们改变一个值:
dup.a = 'Apple';
This statement will also change a
from orig
, since we have a shallow copy, or a reference to var orig
. This means, you're losing the original data as well.
此语句也a
将从更改orig
,因为我们有一个浅拷贝,或对 var 的引用orig
。这意味着,您也会丢失原始数据。
But, creating a brand new variable by using the properties from the original orig
variable, you can create a deep copy.
但是,通过使用原始orig
变量的属性创建一个全新的变量,您可以创建一个深层副本。
var dup = { a: orig.a, b: orig.b, c: orig.c }; //Deep copy!
Now if you change dup.a
, it will only affect dup
and not orig
.
现在如果你改变dup.a
,它只会影响dup
而不是orig
。