2017-09-14 62 views
0

我想將this.companies [i]推入this.companyForFlyers,但由於這是異步的,我總是在變量i中得到錯誤的值(當我調試代碼時,我總是-1)。如何解決這個問題?如何訪問閉包打印文件中的循環索引?

else if (category == "Favorite") { 
    for (var i = this.companies.length - 1; i >= 0; i--) { 
    this.storage.get(this.companies[i].CompanyName).then(val => { 
     if (val == "true"){ 
     this.companyForFlyers.push(this.companies[i]) 
     } 
    }); 
    } 
    return; 
} 

回答

2

的問題是,與var聲明的變量是函數作用域,所以隨後的由環路所做的更改將在由環路捕獲的的i值中反映出來。改用let來創建一個塊範圍變量。

for (let i = this.companies.length - 1; i >= 0; i--) { 
    this.storage.get(this.companies[i].CompanyName).then(val => { 
     if (val == "true"){ 
     this.companyForFlyers.push(this.companies[i]) 
     } 
    }); 
}