在JS中,当slice()文档看起来像深层副本时,为什么会说它是浅层副本? [英] In JS, why does the slice() documentation say it is a shallow copy when it looks like a deep copy?

查看:72
本文介绍了在JS中,当slice()文档看起来像深层副本时,为什么会说它是浅层副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 在JavaScript中,slice()方法将数组的一部分的浅表副本返回到新数组中.据我了解,浅表副本将仅复制数组中的顶级元素,而不会复制嵌套的元素.但是,当我在浏览器控制台中运行测试时,可以肯定slice()方法看起来实际上是在复制嵌套的元素(深度复制).

According to the docs for Array.prototype.slice() in JavaScript, the slice() method returns a shallow copy of a portion of an array into a new array. It is my understanding that a shallow copy will only copy top level elements in an array and will not copy nested elements. However, when I run a test in my browser console, it sure looks like the slice() method is actually copying the nested elements (deep copying).

我在哪里误解了深拷贝的概念?请帮助我澄清一下,因为它与我的具体示例有关.

Where am I misunderstanding the concept of a deep copy? Please help me clarify as it relates to my exact example.

var array = [1,2,[3,4,[5,6]]];
var array2 = array.slice();

推荐答案

在这种情况下,浅表副本意味着嵌套对象将指向原始值.因此,通过修改切片数组中的嵌套对象,您将对原始对象进行变异.

In this case the shallow copy means that the nested objects will be pointing to the original values. So by modifying nested objects in the sliced array, you will mutate the original.

最好看一下示例:

var originalArray = [1, [2, 3], 4];
var slicedArray = originalArray.slice();
var nestedArray = slicedArray[1]; // [2, 3]
nestedArray.push("oh no, I mutated the original array!");
console.log(originalArray); // [1, [2, 3, "oh no, I mutated the original array!"], 4]

这篇关于在JS中,当slice()文档看起来像深层副本时,为什么会说它是浅层副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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