AngularJS数组的和



我在AngularJS中有一个数组,它是从WCF服务中获得的。我可以使用下面这样的函数来实现数组的和。参考:计算AngularJS ng repeat 中重复元素的总和

$scope.getTotal = function(){
    var total = 0;
    for(var i = 0; i < $scope.cart.products.length; i++){
        var product = $scope.cart.products[i];
        total += (product.price);
    }
    return total;
}

但是,有没有任何方法可以在没有过滤器的情况下实现这一点?就像$scope.cart.products.price.Sum()一样?我已经在代码中使用了很多过滤器和函数,希望减少它的数量。

使用reduce

$scope.cart.products.reduce(function(acc,current){
    return acc + current.price;
},0);

或者在ES6:中

$scope.cart.products.reduce((acc,current) => acc + current.price, 0);

查看此处了解有关reduce的MDN文档。

最新更新