传播会创建浅拷贝吗?

ove*_*nge 2 deep-copy shallow-copy typescript ecmascript-6

根据此处给出的示例,

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}`);
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

文件说:传播创造了一个浅拷贝firstsecond。我怎么理解这个?

CRi*_*ice 11

在您的情况下,浅拷贝和深拷贝是相同的。对于仅包含基元的数组,它们将始终相同。只有当您的数组包含其他对象时,您才会注意到差异。

Javascript是按值传递的,所以当一个数组被浅拷贝(比如使用spread)时,原始数组中的每个值都会被复制到新数组中。在原始值的情况下,值被直接复制并且对其所做的更改对原始值没有影响。

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

下面是一个例子:

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);
Run Code Online (Sandbox Code Playgroud)