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

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

    Create a filter of the original array in the arrayCopy. So that changes to the new array won't affect original array.

    var myArray = ['a', 'b', 'c'];
    var arrayCopy = myArray.filter(function(f){return f;})
    arrayCopy.splice(0, 1);
    alert(myArray); // alerts ['a','b','c']
    alert(arrayCopy); // alerts ['b','c']
    

    Hope it helps.

提交回复
热议问题