Javascript 迭代变量i,角度不同
我曾多次无意中发现这一点,但似乎找不到一个好的解决方案:Javascript 迭代变量i,角度不同,javascript,angularjs,q,deferred,Javascript,Angularjs,Q,Deferred,我曾多次无意中发现这一点,但似乎找不到一个好的解决方案: for (var i = types.length - 1; i >= 0; i--) { api.get("test").then(function(res){ // do something with i here $scope.var[i] = res; }); }; 触发then()函数时,迭代已经完成,因此只使用$scope.var[0],而不是$scope.var[1]、
for (var i = types.length - 1; i >= 0; i--) {
api.get("test").then(function(res){
// do something with i here
$scope.var[i] = res;
});
};
触发then()函数时,迭代已经完成,因此只使用$scope.var[0],而不是$scope.var[1]、$scope.var[2]等
我所能想到的就是要么将I变量作为参数提供给函数,然后用deferred返回它,要么使用回调,但两者都不是很好。有解决方案吗?一种方法是将其包装在匿名函数中,以强制
i
绑定到迭代值:
for (var i = types.length - 1; i >= 0; i--) {
(function (actual_i) {
api.get("test").then(function(res){
// do something with i here
$scope.var[actual_i] = res;
});
}(i));
};
由于使用带有回调的map
函数在数组上循环,因此将免费提供绑定:
types.map(function (value, i) {
api.get("test").then(function(res){
// do something with i here
$scope.var[i] = res;
});
});
直截了当地提出简单有效的解决方案。非常感谢你!当然,“javascript中的数组有一个.map函数”,至少从ECMA-262第5版开始就有了
Array.prototype.map()
不是Angular的一个功能。给你:是的,很好的表格,Array.prototype.map()
仍然不是Angular的一个功能。没错,Angular使用它自己的内部映射函数。