我有这样的东西:

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

当前回答

这里有一个我觉得更灵活的解决办法:

function sumOfArrayWithParameter (array, parameter) {
  let sum = null;
  if (array && array.length > 0 && typeof parameter === 'string') {
    sum = 0;
    for (let e of array) if (e && e.hasOwnProperty(parameter)) sum += e[parameter];
  }
  return sum;
}

要得到和,只需像这样使用它:

let sum = sumOfArrayWithParameter(someArray, 'someProperty');

其他回答

我已经在用jquery了。但我认为这已经足够直观了:

var total_amount = 0; 
$.each(traveler, function( i, v ) { total_amount += v.Amount ; });

这基本上只是@akhouri回答的简写版本。

我知道这个问题已经有了一个公认的答案,但我认为我应该加入一个使用数组的替代方案。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');

小提琴

从对象数组

function getSum(array, column)
  let values = array.map((item) => parseInt(item[column]) || 0)
  return values.reduce((a, b) => a + b)
}

foo = [
  { a: 1, b: "" },
  { a: null, b: 2 },
  { a: 1, b: 2 },
  { a: 1, b: 2 },
]

getSum(foo, a) == 3
getSum(foo, b) == 6

提高可读性和使用Map和Reduce的替代方案:

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

const sum = traveler
  .map(item => item.amount)
  .reduce((prev, curr) => prev + curr, 0);

可重用功能:

const calculateSum = (obj, field) => obj
  .map(items => items.attributes[field])
  .reduce((prev, curr) => prev + curr, 0);

我想我应该在这一点上发表我的意见:这是那些应该始终是纯函数式的操作之一,不依赖于任何外部变量。有几个已经给出了很好的答案,使用减法是这里要走的路。

既然我们大多数人已经可以使用ES2015语法,下面是我的建议:

const sumValues = (obj) => Object.keys(obj).reduce((acc, value) => acc + obj[value], 0);

我们把它变成了一个不可变函数。reduce在这里所做的很简单: 从累加器的值0开始,并将当前循环项的值加到累加器中。

函数式编程和ES2015太棒了!:)