Why does changing an Array in JavaScript affect copies of the array?

后端 未结 11 1867
礼貌的吻别
礼貌的吻别 2020-11-22 00:16

I\'ve written the following JavaScript:

var myArray = [\'a\', \'b\', \'c\'];
var copyOfMyArray = myArray;
copyOfMyArray.splice(0, 1);
alert(myArray); // aler         


        
11条回答
  •  面向向阳花
    2020-11-22 00:38

    An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.

    Your comparison with the number example is not correct btw. You assign a new value to copyOfMyNumber. If you assign a new value to copyOfMyArray it will not change myArray either.

    You can create a copy of an array using slice [docs]:

    var copyOfMyArray = myArray.slice(0);
    

    But note that this only returns a shallow copy, i.e. objects inside the array will not be cloned.

提交回复
热议问题