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

后端 未结 11 1856
礼貌的吻别
礼貌的吻别 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:29

    Well, the only possible answer — and the correct one — is that you're not actually copying the array. When you write

    var copyOfArray = array;
    

    you're assigning a reference to the same array into another variable. They're both pointing at the same object, in other words.

提交回复
热议问题