Javascript AngularJS-For循环错误递增,即使数组中只有一个项

Javascript AngularJS-For循环错误递增,即使数组中只有一个项,javascript,angularjs,angular-services,Javascript,Angularjs,Angular Services,在我的angular应用程序中,我有这样一段代码 for (var i = 0; i < $scope.itemList.length; i++) { if ($scope.itemList[i].serialNumber == quickCode) { console.log(i) returnsService.getNoReceiptErrorMessages($scope.itemList[i].sku, quickCode).then(fun

在我的angular应用程序中,我有这样一段代码

for (var i = 0; i < $scope.itemList.length; i++) {
    if ($scope.itemList[i].serialNumber == quickCode) {
        console.log(i)
        returnsService.getNoReceiptErrorMessages($scope.itemList[i].sku, quickCode).then(function (response) {
            console.log(i)

            }
    }
}
for(变量i=0;i<$scope.itemList.length;i++){
if($scope.itemList[i].serialNumber==quickCode){
控制台日志(i)
returnsService.getNoReceiptErrorMessages($scope.itemList[i].sku,quickCode)。然后(函数(响应){
控制台日志(i)
}
}
}
它只是一个
for循环
,在循环中有一个角度服务来调用后端api。
数组只有一个项。因此
i
的值应始终为
0
。但是
console.log(i)
服务调用前打印
0
服务调用后打印
1
。有人能指出这里发生了什么吗。

传递给
回调
。然后
方法是一个闭包,当异步调用发生时,for循环将继续运行,计数器将继续递增

闭包执行上下文有一个指向外部作用域及其所有变量的指针,您在这里体验到的是,当启动回调以及
控制台.log
时,循环已经完成,i计数器(在执行上下文中可用)将等于数组的大小1

要在回调中保留实际计数器,可以将服务调用包装在立即调用的函数(创建隔离作用域)中,并将实际计数器作为参数传递

(function(count){ 
  //here i will be detached scoped to this function
  returnsService.getNoReceiptErrorMessages($scope.itemList[count].sku, 
   quickCode).then(function (response) {
    console.log(count)
  }
})(i)

这是闭包的问题,这就是为什么
let
()出现的原因,用let替换
var,将解决您的问题。
或者,如果您不使用ECMA6,请附上您的电话,如:

(function(variable){
  // variable scope remain intact here 
})(variable)
这是你的具体问题


我认为这是由于js for循环的性质和作用域。说明了循环后I将为1;我相信回调将引用运行时I的状态,即1,而不是传递的I。我将尝试将其表述为正确的答案