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

后端 未结 3 469
暗喜
暗喜 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:10

    In this case the shallow copy means that the nested objects will be pointing to the original values. So by modifying nested objects in the sliced array, you will mutate the original.

    It's better to see on the example:

    var originalArray = [1, [2, 3], 4];
    var slicedArray = originalArray.slice();
    var nestedArray = slicedArray[1]; // [2, 3]
    nestedArray.push("oh no, I mutated the original array!");
    console.log(originalArray); // [1, [2, 3, "oh no, I mutated the original array!"], 4]
    

提交回复
热议问题