对数组中的属性值求和的更好方法 [英] Better way to sum a property value in an array
问题描述
我有这样的事情:
$scope.traveler = [
{ description: 'Senior', Amount: 50},
{ description: 'Senior', Amount: 50},
{ description: 'Adult', Amount: 75},
{ description: 'Child', Amount: 35},
{ description: 'Infant', Amount: 25 },
];
现在有了这个数组的总数量,我正在做这样的事情:
Now to have a total Amount of this array I'm doing something like this:
$scope.totalAmount = function(){
var total = 0;
for (var i = 0; i < $scope.traveler.length; i++) {
total = total + $scope.traveler[i].Amount;
}
return total;
}
当只有一个数组时很容易,但我有其他数组具有不同的属性名称,我想求和.
It's easy when is only one array, but I have others arrays with a different property name that I would like to sum.
如果我能做这样的事情,我会更开心:
I would be happier If I could do something like this:
$scope.traveler.Sum({ Amount });
但我不知道如何以一种将来可以像这样重复使用它的方式来解决这个问题:
But I don't know how to go through this in a way that I could reuse it in the future like this:
$scope.someArray.Sum({ someProperty });
推荐答案
更新答案
由于向 Array 原型添加函数的所有缺点,我正在更新此答案以提供一种替代方法,使语法与问题中最初请求的语法相似.
Due to all the downsides of adding a function to the Array prototype, I am updating this answer to provide an alternative that keeps the syntax similar to the syntax originally requested in the question.
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 原型中添加一个函数.
Since it is an array you could add a function to the Array prototype.
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/
这篇关于对数组中的属性值求和的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!