Does Spreading create shallow copy?

前端 未结 3 588
孤城傲影
孤城傲影 2020-11-30 15:05

As per the example given here,

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

let both_plus:number[] = [0, ...first, ...second, 5];
console.log(         


        
3条回答
  •  一整个雨季
    2020-11-30 15:39

    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 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.

    Here's an example:

    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);

提交回复
热议问题