问题描述:如下面代码,arr[i]的值前后不一致
var arr=[{age:10},{age:20}]
for (var i in arr){ //lenth=2,循环两次
console.log(arr[i]) //{age:10},{age:20}
sgtbService_sgtbcx(arr[i].age).then(res=>{
console.log(arr[i]) //两个都是{age:20}
})
}
解决方法一:用let定义i,不能用var来定义
for (let i in arr){ //lenth=2,循环两次
console.log(arr[i]) //{age:10},{age:20}
sgtbService_sgtbcx(arr[i].age).then(res=>{
console.log(arr[i]) //{age:10},{age:20}
})
}
解决方法二:把请求接口部分的代码提取成单独的function,在for循环中调用此function
for (var i in arr){ //lenth=2,循环两次
console.log(arr[i]) //{age:10},{age:20}
this.test(arr[i]); //通过调用test方法来请求接口
}
test(row){
sgtbService_sgtbcx(row.age).then(res=>{
console.log(row) //{age:10},{age:20}
})
}