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

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

    An array, or an object in javascript always holds the same reference unless you clone or copy. Here is an exmaple:

    http://plnkr.co/edit/Bqvsiddke27w9nLwYhcl?p=preview

    // for showing that objects in javascript shares the same reference
    
    var obj = {
      "name": "a"
    }
    
    var arr = [];
    
    //we push the same object
    arr.push(obj);
    arr.push(obj);
    
    //if we change the value for one object
    arr[0].name = "b";
    
    //the other object also changes
    alert(arr[1].name);
    

    For object clone, we can use .clone() in jquery and angular.copy(), these functions will create new object with other reference. If you know more functions to do that, please tell me, thanks!

提交回复
热议问题