循环返回总是相同的最后一个值

时间:2017-06-21 13:07:06

标签: angular typescript angular-material

我创建一个循环来创建对象。

Action.ts

public campaing:any = {
    'id': '',
    'campaing_code': '',
    'campaing_type': '',
    'start_date': this.currentDate,
    'end_date': this.currentDate,
    'deadline': this.currentDate,
    'creation_date': this.currentDate,
    'special': false,
    'os': '',
    'country': '',
    'campaing_country': 'germany',
    'version_app': '',
    'permanent_promo': false,
    'promo_tag': 'ABS-W-',
    'editor_name': '',
    'plus_promotag': '',
    'status': 'Successful',
    'application': {},
    'publisher': {},
    'contact': '',
    'sended': false
  };
  public searchparram: any = {
    'type': '',
    'time': '',
    'start_date': this.currentDate,
    'deadline': this.currentDate,
    'publisher': {},
    'wildcard': false,
    'os': '',
    'category': '',
    'number_campaings': 1
  }
public suggescampaings:any = [];      
public generateCampaings(){
        this.campaing.campaing_code = this.searchparram.type;
        this.campaing.start_date = this.searchparram.start_date;
        this.campaing.deadline = this.searchparram.deadline;
        this.campaing.publisher = this.searchparram.publisher;
        this.campaing.os = this.searchparram.os;
        for (let i = 1; i <= this.searchparram.number_campaings; i++) {
          ((i)=>{
            this.campaing.id = i; /* Here should print i but alway print the last value of i */
            this.suggescampaings.push(this.campaing);
          })(i);
        }
      }

但是当我尝试放入camaping.id = i时,总是返回迭代的最后一个值。我的意思是如果迭代是8次总是给出id 8。

所以我的想法是将迭代作为id,然后将对象推入数组。

2 个答案:

答案 0 :(得分:1)

问题是您在每个循环中修改相同的this.campaing对象。如果您打算为每个循环推送一个新对象,则可以使用Object.assign轻松创建副本:

for (let i = 1; i <= this.searchparram.number_campaings; i++) {
  ((i) => {
    let copy = Object.assign({}, this.campaing);
    copy.id = i;
    this.suggescampaings.push(copy);
  })(i);
}

答案 1 :(得分:0)

问题不在于循环,这是因为在将对象推入数组suggescampaings之前没有创建新对象。同一个对象campaing被多次覆盖,如果你显示数组,它将多次显示同一个对象(即最后一个对象)。

建议:每次在循环内创建新的临时对象,然后将其推入数组。