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