复制 angular 中的对象数组 2

Copy array of Objects in angular 2

我有两个名为 'persons' 和 'persons2' 的数组, 'persons2' 数组将是 'persons' 数组的副本, 但问题是当我复制它时,我想改变第二个数组,第一个数组也在改变。这是我的代码:

  export class AppComponent {

  persons = [
    {
      name:'David',
      lname:'Jeu'
    }
  ];

  persons2=[...this.persons];

  constructor(){
      console.log(this.persons[0]);
      this.persons2[0].name='Drake';
      console.log(this.persons[0]);

      console.log(this.persons2[0]);
  }

}

But the problem is when I copy it, and I want to change the second array, the first array is also changing

那是因为两个数组中的对象共享相同的引用。要执行深层复制,请尝试以下操作:

let persons2 = person.map(x => Object.assign({}, x));

let person2 = JSON.parse(JSON.stringify(person));

在你的例子中,两个数组都指的是同一个内存,这通常被称为浅拷贝。

您可以深拷贝第一个数组,然后更改第二个数组。这对第一个阵列没有影响。

let persons = [{
  name: 'David',
  lname: 'Jeu'
}];

let persons2 = JSON.parse(JSON.stringify(persons));
persons2[0].age = 29;

console.log(persons)
console.log(persons2)

对于这类操作,通常明智的做法是使用 Lodash Clonedeep