浅拷贝和带有JavaScript数组的深拷贝有什么区别?

编程入门 行业动态 更新时间:2024-10-25 08:15:46
本文介绍了浅拷贝和带有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数组的深拷贝有什么区别?

本文发布于:2023-07-28 14:07:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1231628.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   有什么区别   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!