javascript pass by reference workaround

前端 未结 2 1922
一个人的身影
一个人的身影 2021-01-22 04:44

let\'s say I\'ve got an array, var animals = [\"dog\",\"cat\",\"rat\"];

then I define var pets = animals;

then I call pets.shift(

2条回答
  •  旧时难觅i
    2021-01-22 05:37

    You have to clone the array, which is done with

    var savedAnimals = animals.slice();
    

    Note that this isn't a deep clone : it doesn't protect the elements inside against modification (if they're not strings).

提交回复
热议问题