gpt4 book ai didi

javascript - Angular/ typescript : arrays in typescript changing when an independent element got changed

转载 作者:行者123 更新时间:2023-11-30 11:17:44 25 4
gpt4 key购买 nike

为什么我的数组元素在更新另一个获取数组中某项副本的变量时更新?

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;
}

最佳答案

它会给你那个对象的引用

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;

关于javascript - Angular/ typescript : arrays in typescript changing when an independent element got changed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50941288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com