为什么另一个获取数组中一项的副本的变量更新我的数组元素?
StackBlitz:https://stackblitz.com/edit/angular-3tgp7h
(检查AppComponent)
代码:
export class AppComponent implements OnInit {
materials: Material[] = [];
material: Material;
ngOnInit(){
this.materials = [
{
name: 'One',
price:10,
},
{
name: 'Two',
price:10,
},
{
name: 'Three',
price:10,
},
];
this.material = this.materials.find(mat => mat.name === 'One');
console.log('material ones price in the array: '+this.materials.find(mat => mat.name === 'One').price )
//Update (single) material object
this.material.price = 20;
// below is displaying 20. but i didn't update array
// why is this happening?
console.log('material ones price in the array after update: '+this.materials.find(mat => mat.name === 'One').price )
}
}
export interface Material {
name: string;
price: number;
}
答案 0 :(得分:3)
它将为您提供该对象的参考
this.material = this.materials.find(mat => mat.name === 'One');
这就是为什么它要更新源数组中的值。
您可以使用以下方式创建深层克隆:
let foundObj = this.materials.find(mat => mat.name === 'One');
if(foundObj) {
foundObj = JSON.parse(JSON.stringify(foundObj));
}
this.material = foundObj;