In JS, why does the slice() documentation say it is a shallow copy when it looks like a deep copy?

后端 未结 3 441
暗喜
暗喜 2021-01-21 19:26

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 under

3条回答
  •  礼貌的吻别
    2021-01-21 20:21

    slice is a shallow copy not because nested values are ignored, but because they contain references to the original arrays, and thus are still linked. For example:

    let arr = [1, [2]]
    let shallowCopy = arr.slice(0, arr.length);
    shallowCopy[1][0] = "foobar";
    
    // will print "foobar", because the nested array is just a reference
    console.log(arr[1][0]);
    

提交回复
热议问题