浅拷贝和带有JavaScript数组的深拷贝有什么区别? [英] What is the difference between a shallow copy and a deep copy with JavaScript arrays?

查看:126
本文介绍了浅拷贝和带有JavaScript数组的深拷贝有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据MDN文档调用 array.slice()将创建数组的浅表副本。

According the MDN documentation calling array.slice() will create a shallow copy of the array.

请参阅此切片的MDN链接()

但是,如果我在控制台中运行一个简单的测试:

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();

并检查shallow_copy,我可以看到整个二维数组似乎被复制了。

and inspect shallow_copy, I can see that the entire 2 dimensional array appears to be copied over.

浅拷贝和深拷贝有什么区别?如果我猜的话,我会把它称为深层副本。

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.

推荐答案

要看到区别,请尝试:

shallow_copy[0][2] = 4;
console.dir(test);

你会看到 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.

深拷贝将递归执行浅拷贝,直到所有内容都是原件的新副本。

A deep copy would recursively perform shallow copies until everything is a new copy of the original.

这篇关于浅拷贝和带有JavaScript数组的深拷贝有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆