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

后端 未结 11 1864
礼貌的吻别
礼貌的吻别 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条回答
  •  梦毁少年i
    2020-11-22 00:31

    You don't have any copies.
    You have multiple variables holding the same array.

    Similarly, you have multiple variables holding the same number.

    When you write copyOfMyNumber = ..., you're putting a new number into the variable.
    That's like writing copyOfMyArray = ....

    When you write copyOfMyArray.splice, you're modifying the original array.
    That isn't possible with numbers because numbers are immutable and cannot be modified,

提交回复
热议问题