2017-06-21 30 views
1

即時創建一個循環來創建對象。循環返回始終是最後一個值

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 =我,總是返回迭代的最後一個值。我的意思是,如果iteraion是8次,總是給id 8。

所以這個想法是把id作爲迭代,然後推入數組中的對象。

+1

因爲你改變了同一個對象('this') – Andreas

+0

當然只會有最後的值。在每個循環中覆蓋'this.campaing.id'。你期望什麼? – Saravana

回答

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); 
} 
+0

完美的工作非常感謝你的幫助。 –

0

問題不在循環中,這是因爲在將對象推入數組suggescampaings之前尚未創建新對象。同一個對象campaing被覆蓋多次,並且如果顯示數組,它將多次顯示相同的對象(即最後一個對象)。

建議:每次在循環中創建新的臨時對象,然後將其推入數組中。

+0

我試圖在循環內創建一個新的臨時對象,但仍然發生同樣的情況。 'let newcampaing:any = {}' 但sitll發生相同。 –

+0

你應該克隆對象以創建臨時對象。所以這個參考是不一樣的。 –