javascript - for循环中无法求和

标签 javascript angularjs for-loop

我在 for 循环 中有一个 Angular 服务,它返回一个对象数组。我想获得该服务返回的值的总和,但最终我什么也没得到。我的服务工作正常,但我的问题是我无法得到总和。下面是我的代码

Controller

var TotalOBValueLand = 0;
for(var i = 0; i < $scope.selectedProp.length; i++){
     AccountService.getTopAccountDetails($scope.selectedProp[i]["propId"]).then(function(msg){
           TotalOBValueLand += parseInt(msg.data[0].OBValueLand);
           //my return data here has no error.
     });
}
console.log(TotalOBValueLand); //I got zero;

最佳答案

使用 Promise.allarray#map 获取结果数组,然后使用 Array#reduce 对它们求和

var TotalOBValueLand = 0;
Promise.all($scope.selectedProp.map(function(prop) {
     return AccountService.getTopAccountDetails(prop).then(function(msg){
           return parseInt(msg.data[0].OBValueLand);
     });
})).then(function(results) {
    TotalOBValueLand = results.reduce(function(a, b) {
       return a + b; 
    });
    console.log(TotalOBValueLand);
});

In response to the comments

var TotalOBValueLand = 0;
var TotalOBValueBuilding = 0;
Promise.all($scope.selectedProp.map(function(prop) {
     return AccountService.getTopAccountDetails(prop).then(function(msg){
           return parseInt(msg.data[0]);
     });
})).then(function(results) {
    TotalOBValueLand = results.reduce(function(a, b) {
       return a.OBValueLand + b.OBValueLand; 
    });
    TotalOBValueBuilding  = results.reduce(function(a, b) {
       return a.OBValueBuilding  + b.OBValueBuilding ; 
    });
    console.log(TotalOBValueLand, TotalOBValueBuilding);
});

and a little more generic

Promise.all($scope.selectedProp.map(function(prop) {
     return AccountService.getTopAccountDetails(prop).then(function(msg){
           return parseInt(msg.data[0]);
     });
})).then(function(results) {
    var totals = results.reduce(function(result, a) {
        Object.keys(a).forEach(function(key) {
            result[key] = (result[key] || 0) + a[key];
        });
        return result;
    }, {});
    console.log(totals.OBValueLand, totals.OBValueBuilding);
});

关于javascript - for循环中无法求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42263624/

相关文章:

javascript - 基于查找值求和二维数组中的值 - Javascript

javascript - 如何在javascript中将异步调用与同步调用结合起来

javascript - AngularJS $scope 和 Controller 作为语法真的没有区别吗?

javascript - 如何为 JavaScript 创建的每个 DIV 制作不同的 insideText?

JavaScript 矩阵

python - 列表打印未按需要进行。制作的图案是逆时针90度

javascript - 如何覆盖 HTMLElement 原型(prototype)上的 getter 函数

javascript - 使用 AngularJS ng-hide 的 UI Bootstrap Alert 占用额外空间

javascript - 使用 ocLazyLoad 延迟加载带有 $stateProvider 的 Controller

javascript - 从 Firebase 加载数据时,AngularJS 过滤器不起作用