javascript - 以 Angular 2 复制对象数组

标签 javascript arrays angular javascript-objects angular-arrays

我有两个名为“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));

关于javascript - 以 Angular 2 复制对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51573579/

相关文章:

javascript - 为什么这个功能不起作用?它正在返回, "undefined"!

java - 自定义对象上的流过滤器多维数组给定范围

javascript - Angular 2将html属性从父级传递给子级

angular - 如何在 rxjs6 中导入 ErrorObservable 或 _throw?扔进 rxjs

javascript - 更改组件 React Web

javascript - 如何删除 Highcharts 极坐标图中条形之间的空白?

python - NumPy loadtxt()

php - 如果键相同,如何组合两个数组并将其分块

javascript - 当我输入一个时,我有几个文本框会填充

javascript - 我可以将信息从浏览器控制台(通过 AJAX)发送到本地/远程主机上的 php 文件吗?