Does Spreading create shallow copy?

前端 未结 3 590
孤城傲影
孤城傲影 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条回答
  •  猫巷女王i
    2020-11-30 15:39

    Shallow copy means that all of the elements from first and second are merely added to the new array, the new copy. Deep copy would mean that all of the elements from first and second are first copied then added to the new array.

    The distinction being whether the elements themselves are copied into a new object before being added to the new array.

    Using primitives, like numbers, it is not really possible to illustrate the difference, but if you use objects the difference is pretty clear.

    Say you have something like this:

    let first = [{foo: 'bar'}];
    let second = [{fizz: 'buzz'}];
    let both = [...first, ...second];
    

    Since spreading results in a shallow copy you can expect the relevant objects to pass an equality test:

    first[0] === both[0]; // true
    second[0] === both[1]; // true
    

    But if spreading resulted in a deep copy you would expect the equality test to fail:

    first[0] === both[0]; // false
    second[0] === both[1]; // false
    

提交回复
热议问题