角度/打字稿:打字稿中的数组会在更改独立元素时发生变化

时间:2018-06-20 06:04:18

标签: javascript arrays angular typescript

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

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

1 个答案:

答案 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;