如何访问闭包打印文件中的循环索引?

问题描述:

我想将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; 
} 

的问题是,与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]) 
     } 
    }); 
}