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

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

    So everyone here has done a great job of explaining why this is happening - I just wanted to drop a line and let you know how I was able to fix this - pretty easily:

    thingArray = ['first_thing', 'second_thing', 'third_thing']
    function removeFirstThingAndPreserveArray(){
      var copyOfThingArray = [...thingArray]
      copyOfThingArray.shift();
      return copyOfThingArray;
    }
    

    This is using the ... spread syntax.

    Spread Syntax Source

    EDIT: As to the why of this, and to answer your question:

    What is the difference between an array and a number in JavaScript that it seems changing an array changes the value of a copy of the array, where as changing a number does not change the value of a copy of the number?

    The answer is that in JavaScript, arrays and objects are mutable, while strings and numbers and other primitives are immutable. When we do an assignment like:

    var myArray = ['a', 'b', 'c']; var copyOfMyArray = myArray;

    copyOfMyArray is really just a reference to myArray, not an actual copy.

    I would recommend this article, What are immutable and mutable data structures?, to dig deeper into the subject.

    MDN Glossary: Mutable

提交回复
热议问题