嗨,我正在尝试将2行存储在数组中,但是第二行正在更新已存储的第一行。
UserRole: UserRoleDTO;
UserRoleArray: UserRoleDTO[];
rolesstring=["1","2"]
this.roleidArray = rolesstring.split(',');
let UserArrayData = [];
let count = 0;
for (let roledata of this.roleidArray) {
this.UserRole.roleid = +roledata;
this.UserRole.userid = +UserId;
this.UserRole.isactive = 1;
this.UserRole.entryby = 1;
console.log('RoleId which need to store in UserArrayData :' + this.UserRole.roleid);
UserArrayData[count] = this.UserRole;
console.log('Data stored in UserArrayData :' + UserArrayData[count].roleid);
count = count + 1;
}
this.UserRoleArray = UserArrayData;
console.log('RoleId which is stored in UserArrayData[0]:' + UserArrayData[0].roleid);// here it is always showing the last roleid stored
UserArrayData [0] .roleid的结果应为1,但显示为2。
答案 0 :(得分:1)
这是深度克隆的问题,因为每当您分配UserArrayData[count] = this.UserRole;
时,它都会分配其引用。因此,要解决此问题,您需要将深层副本分配给Object.assign。
尝试一下:
UserArrayData[count] = Object.assign({}, this.UserRole);
或者按照@JB的建议,您可以在fol循环内创建局部变量。
尝试一下:
for (let roledata of this.roleidArray) {
let tmpObj = this.UserRole;
tmpObj.roleid = +roledata;
tmpObj.userid = +UserId;
tmpObj.isactive = 1;
tmpObj.entryby = 1;
console.log('RoleId which need to store in UserArrayData :' + tmpObj.roleid);
UserArrayData[count] = this.UserRole;
console.log('Data stored in UserArrayData :' + UserArrayData[count].roleid);
count = count + 1;
}