首页 > 解决方案 > 为什么推送到具有结构的数组有效但使用 json 推送却不行?

问题描述

以下代码有效:

private memberOf: PersonCommittee = {
    personcommitteeid: null,
    pkpersonid: null,
    committeeid: null,
    ismember: false,
    isexofficio: false,
    active: true,
  }

private personcomittee[] = PersonCommittee[];

addCommittee() {
  this.memberOf.pkpersonid = this.pkpersonid;
  this.memberOf.committeeid = id;
  this.memberOf.ismember = true;
  this.memberOf.isexofficio = true;
  this.memberOf.active = true;
  this.personcommittees.push( {
      "pkpersonid": this.memberOf.pkpersonid,
      "committeeid": this.memberOf.committeeid,
      "ismember": this.memberOf.ismember,
      "isexofficio": this.memberOf.isexofficio,
      "active": this.memberOf.active
  });
}

但这不会:

addCommittee() {
  this.memberOf.pkpersonid = this.pkpersonid;
  this.memberOf.committeeid = id;
  this.memberOf.ismember = true;
  this.memberOf.isexofficio = true;
  this.memberOf.active = true;
  this.personcommittees.push(this.memberOf);
}

第二个代码示例将新值推送到数组,但将所有值更改为新值。

因此,例如,如果我有一个委员会 ID 为 3 并且想要添加另一个委员会 ID 为 4 的委员会,第一个示例创建了一个显示两者的 personcommittee 数组,但第二个示例创建了一个包含两个委员会 ID 为 4 的记录的数组。

this.memberOf 的结构正确。在第二个示例中,结构被推送到数组中,但它覆盖了所有先前的数据。

为什么?

标签: javascriptangularmultidimensional-array

解决方案


推荐阅读