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

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

问题描述

根据 MDN 文档调用 array.slice() 将创建数组的浅拷贝.

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

请参阅此 关于 slice() 的 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天全站免登陆