我有这样的东西:
$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 });
map()
方法获取每个元素的myProperty
属性值,并用reduce()
方法对这些值求和。简而言之,它计算了该数组中所有对象的myProperty
属性值之和。 - ashleedawg