Angular 9 在数组中添加多个对象覆盖现有数组

Angular 9 Adding Multiple Objects in an array overrides the existing array

我正在使用 Angular 9 并尝试在数组中添加多个对象。但是我看到在添加新对象时,现有对象也会发生变化。我怀疑这是因为数组引用了对象。

我该如何更改它。

代码:

userModel: UserModel = new UserModel()
userArray: any = new Array()

.....codes..constructors....oninits etc...

submit(){
    this.userModel.name = "Hello"
    this.userModel.age = "25"
    this.userModel.area = "IN"

    this.userArray.push(this.userModel)

    this.userModel.name = "World"
    this.userModel.age = "26"
    this.userModel.area = "WB"

    this.userArray.push(this.userModel)
}

输出是

[{'name':'世界, 'age':'26', 'area':'WB'},{'name':'世界, 'age':'26', 'area':'WB'}]

我要的是

[{'name':'你好,'age':'25', 'area':'IN'},{'name':'世界,'age':'26', 'area':'WB'}]

您每次都将相同的引用推入数组 (this.userModel),而没有重新分配给不同的对象。因此,this.userArray[0] 和 this.userArray[1] 是同一个对象,对一个索引或 this.userModel 处的项目所做的更改将影响另一个。尝试

submit(){
    this.userModel.name = "Hello"
    this.userModel.age = "25"
    this.userModel.area = "IN"

    this.userArray.push(this.userModel)

    this.userModel = {} as any; // reassign the reference to a new Object

    this.userModel.name = "World"
    this.userModel.age = "26"
    this.userModel.area = "WB"

    this.userArray.push(this.userModel)
}

正如@Kaustubh 所说,您只是在更改同一个对象并将其再次推入数组。

执行此操作的另一种方法是在推送时使用展开运算符来复制对象,而不是推送原始对象。我更喜欢这个,因为数组以副本而不是原始对象结束。

submit() {
    this.userModel.name = "Hello"
    this.userModel.age = "25"
    this.userModel.area = "IN"

    this.userArray.push({ ...this.userModel })

    this.userModel.name = "World"
    this.userModel.age = "26"
    this.userModel.area = "WB"

    this.userArray.push({ ...this.userModel })
}

而不是 this.userArray.push(this.userModel), 您必须在这两个地方将其更改为 this.userArray.push({ ...this.userModel })

这将修复您的错误。

你犯的错误是:

userModel 变量存储对对象的引用,当您执行 this.userArray.push(this.userModel).

时,相同的对象被推送为对数组的引用

因此,如果您再次更改 userModel,您将更改所有其他变量引用的对象。

当你访问this.userModel.name时指的是同一个对象。因此,您需要在推送到数组之前创建一个新的 UserModel 对象并设置值。

你可以像下面这样简单地做

submit() {
    this.userModel.name = "Hello"
    this.userModel.age = "25"
    this.userModel.area = "IN"

    this.userArray.push({...this.userModel})

    this.userModel.name = "World"
    this.userModel.age = "26"
    this.userModel.area = "WB"

    this.userArray.push({...this.userModel})
}