传播会产生浅拷贝吗? [英] Does Spreading create shallow copy?

查看:73
本文介绍了传播会产生浅拷贝吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据给出的示例,此处

let first:number[] = [1, 2];
let second:number[] = [3, 4];

let both_plus:number[] = [0, ...first, ...second, 5];
console.log(`both_plus is ${both_plus}`);
first[0] = 20;
console.log(`first is ${first}`);
console.log(`both_plus is ${both_plus}`);
both_plus[1]=30;
console.log(`first is ${first}`);
console.log(`both_plus is ${both_plus}`);

展开显示深层副本,因为基于以下输出,所有三个数组都有其自己的重复项:

Spreading shows a deep copy, because all three array's have it's own duplicates, based on below output:

both_plus is 0,1,2,3,4,5
first is 20,2
both_plus is 0,1,2,3,4,5
first is 20,2
both_plus is 0,30,2,3,4,5

文档说:传播会创建浅表副本firstsecond .我怎么理解的?

Documentation says: Spreading creates a shallow copy of first and second. How do I understand this?

推荐答案

在您的情况下,浅表副本和深表副本是相同的.对于仅包含基元的数组,它们将始终相同.您只会在数组包含其他对象时注意到差异.

In your case a shallow copy and deep copy are the same. For an array containing only primitives, they will always be identical. You'll only notice the difference when your array contains other objects.

Javascript是按值传递的,因此当数组被浅复制(例如通过使用spread)时,原始数组中的每个值都将被复制到新数组中.对于原始类型,该值将直接复制,对其进行的更改不会影响原始值.

Javascript is pass by value, so when an array is shallow copied (such as by using spread), each value in the original array is copied to the new array. In the case of a primitive, the value is copied directly and changes made to it have no effect on the original.

但是,当数组包含对象时,每个值本身就是对其他内容的引用.因此,即使引用已复制到新数组中,它仍指向与原始数组中引用相同的内容.因此,虽然对新数组进行变异不会更改原始数组,但是对数组元素进行变异会影响原始数组.

However, when the array contains objects, each value is itself a reference to something else. So even though the reference has been copied to a new array, it still points to the same thing as the reference in the original array. So while mutating the new array will not change the original, mutating the elements of the array will affect the original.

这是一个例子:

const objArray = [{foo: "bar"}];
const shallowCopy = [...objArray];

// Changing the array itself does not change the orignal. Note the
// original still only has one item, but the copy has two:
shallowCopy.push({foo: "baz"});
console.log("objArray after push:", objArray);
console.log("shallowCopy after push:", shallowCopy);

// However, since shallowCopy[0] is a reference pointing to the same object
// as objArray[0], mutating either will change the other:
shallowCopy[0].foo = "something else";
console.log("objArray after mutation:", objArray);
console.log("shallowCopy after mutation:", shallowCopy);

这篇关于传播会产生浅拷贝吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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