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

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

    The issue with shallow copy is that all the objects aren't cloned, instead it get reference.So array.slice(0) will work fine only with literal array, but it will not do shallow copy with object array. In that case one way is..

    var firstArray = [{name: 'foo', id: 121}, {name: 'zoo', id: 321}];
    var clonedArray = firstArray.map((_arrayElement) => Object.assign({}, _arrayElement));  
    console.log(clonedArray);
    // [{name: 'foo', id: 121}, {name: 'zoo', id: 321}]  // shallow copy
    

提交回复
热议问题