对数组中的属性值求和的更好方法

新手上路,请多包涵

我有这样的事情:

$scope.traveler = [
            {  description: 'Senior', Amount: 50},
            {  description: 'Senior', Amount: 50},
            {  description: 'Adult', Amount: 75},
            {  description: 'Child', Amount: 35},
            {  description: 'Infant', Amount: 25 },
];

现在有了这个数组的总量,我正在做这样的事情:

$scope.totalAmount = function(){
       var total = 0;
       for (var i = 0; i < $scope.traveler.length; i++) {
              total = total + $scope.traveler[i].Amount;
            }
       return total;
}

当只有一个数组时很容易,但我有其他数组具有不同的属性名称,我想总结一下。

如果我能做这样的事情,我会更开心:

$scope.traveler.Sum({ Amount });

但我不知道如何以一种我可以在未来重用它的方式来完成它,如下所示:

$scope.someArray.Sum({ someProperty });

原文由 nramirez 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 741
2 个回答

更新的答案

由于向 Array 原型添加函数的所有缺点,我正在更新此答案以提供一种替代方法,使语法与问题中最初请求的语法相似。

 class TravellerCollection extends Array {
 sum(key) {
 return this.reduce((a, b) => a + (b[key] || 0), 0);
 }
 }
 const traveler = new TravellerCollection(...[
 { description: 'Senior', Amount: 50},
 { description: 'Senior', Amount: 50},
 { description: 'Adult', Amount: 75},
 { description: 'Child', Amount: 35},
 { description: 'Infant', Amount: 25 },
 ]);

 console.log(traveler.sum('Amount')); //~> 235

原始答案

由于它是一个数组,因此您可以向 Array 原型添加一个函数。

 traveler = [
 { description: 'Senior', Amount: 50},
 { description: 'Senior', Amount: 50},
 { description: 'Adult', Amount: 75},
 { description: 'Child', Amount: 35},
 { description: 'Infant', Amount: 25 },
 ];

 Array.prototype.sum = function (prop) {
 var total = 0
 for ( var i = 0, _len = this.length; i < _len; i++ ) {
 total += this[i][prop]
 }
 return total
 }

 console.log(traveler.sum("Amount"))

小提琴:http: //jsfiddle.net/9BAmj/

原文由 bottens 发布,翻译遵循 CC BY-SA 4.0 许可协议

我知道这个问题有一个公认的答案,但我想我会加入一个使用 array.reduce 的替代方案,看到对数组求和是 reduce 的典型示例:

 $scope.sum = function(items, prop){
    return items.reduce( function(a, b){
        return a + b[prop];
    }, 0);
};

$scope.travelerTotal = $scope.sum($scope.traveler, 'Amount');

小提琴

原文由 Gruff Bunny 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题