在Angular 2中复制对象数组

4

我有两个数组,分别叫做'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]);
  }

}

1
每个问题都有重复... - Akxe
3个回答

8

但问题是当我复制它并且想要更改第二个数组时,第一个数组也会改变。

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

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

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

谢谢,它正在工作。但是为什么这段代码不起作用?persons2=[...this.persons]; - Jack
1
@Jack,这是因为person和person2内部的对象共享同一引用。因此,在一个对象中所做的更改将反映在另一个对象中。 - amrender singh
我做了 :)。我正在观看这个YouTube教程:https://www.youtube.com/watch?v=1tRLveSyNz8,在2:07:00处,他和我做了一样的事情,而且对他起作用了。你能解释一下吗? - Jack
@Jack 确实会很喜欢 :-) - amrender singh
@Jack,请在视频中继续前进,指南已经提到,在新的“数组”上进行添加和删除操作不会反映在旧数组中。但是,新数组和旧数组中现有的对象保持不变。也就是说,在您的情况下,如果您在person2两个数组中添加/删除一个对象,它将不会从person数组中添加/删除。 - amrender singh

1
在您的情况下,两个数组都指向相同的内存,这通常被称为浅拷贝。

enter image description here

You can make a deep copy of the first array and then change the second array. That will have no impact on the first array.

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

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

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


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接