开发者社区 问答 正文

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

我有这样的事情:

$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 });

展开
收起
保持可爱mmm 2020-02-07 00:05:51 524 分享 版权
1 条回答
写回答
取消 提交回答
  • 由于将函数添加到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

    问题来源于stack overflow

    2020-02-07 00:06:13
    赞同 展开评论
问答地址: