简体   繁体   English

Angular 2:Array.push 无法正常工作

[英]Angular 2: Array.push not working properly

When i push the item into the array, item is pushed but problem is that all items in array becomes same as the last item pushed.当我将项目推入阵列时,项目被推入但问题是阵列中的所有项目变得与最后推入的项目相同。

pushspecification() {
        this.specificationSaveDetailList.push(this.specificationsaveDetail);
    }

Here is the plunker code: plunker_Code这是plunker代码: plunker_Code
In this plunker example i select item from the dropdown and provide the description and click add button and table is populated with array item.在这个 plunker 示例中,我从下拉列表中选择项目并提供描述并单击添加按钮,表格中填充了数组项目。

Because you are binding pushing same object with its reference to an array element.因为您正在绑定推送相同的对象及其对数组元素的引用。 So when you are updating specificationsaveDetail object reference it updates the all elements of array as they are references of same element.因此,当您更新specificationsaveDetail对象引用时,它会更新数组的所有元素,因为它们是同一元素的引用。

To make it work, you have to create a new object copy and push it inside array.要使其工作,您必须创建一个新的对象副本并将其推送到数组中。 For then same you could use Object.assign同样你可以使用Object.assign

pushspecification() {
    this.specificationSaveDetailList.push(Object.assign({}, this.specificationsaveDetail));
}

Demo Plunker演示 Plunker

你可以这样使用:

Array.push(Object.assign({}, this.utility));

Use the below approach for when you are adding the elements into array.将元素添加到数组时,请使用以下方法。

const element: IEmployee[] = []; //initialize the array
element.push(employee);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM