如何在迭代中求和值

时间:2016-11-11 00:06:15

标签: javascript angularjs arrays

我有数组$scope.otherDetailsData

[0] object 
amount: 29.9
code: "012"
currency: "BRL"
payedDate: "2016-11-10"
roDate: "2016-08-01"
type:"OTHER"

[1] object
amount: 39.9
code: "013"
currency: "BRL"
payedDate: "2016-11-11"
roDate: "2016-08-01"
type:"OTHER"

我的问题是,我怎样才能将总量的变量加总? 例如:69.8

<span> {{ totalOfSumAmount }} </span>

3 个答案:

答案 0 :(得分:0)

最简单(也是最有效)的方法就是编写一个为您完成此功能的函数。

<span> {{ getTotalOfSumAmount() }} </span>

将功能添加到控制器:

$scope.getTotalOfSumAmount = function () {
    var runningTotal = 0;
    for (var i = 0; i < $scope.otherDetailsData.length; i++) {
        runningTotal += $scope.otherDetailsData[i].amount;
    }
    return runningTotal;
}

答案 1 :(得分:0)

您可以使用Array.prototype.reduce

$scope.totalOfSumAmount = $scope.otherDetailsData.reduce(function(prev, curr) {
  return prev + curr.amount;
}, 0);

答案 2 :(得分:0)

使用array.reduce()对结果求和。例如:

    $scope.totalOfSumAmount =   $scope.items.reduce(function(carry, currentItem) {
      //add the amount from the current item to the running total (carry)
      return carry + currentItem.amount;
    }, 0);//0 is the initial value

该回调函数(即示例中的function(carry, currentItem) {...)实际上可以接受四个参数:

  • 上一个值 - 上一次迭代的值(或初始值)
  • 当前值 - 数组中的当前元素
  • 当前索引 - 数组中当前元素的当前索引
  • 原始数组 - 我们正在迭代的数组

第二个参数(可选)是初始值,因此,例如,如果我们需要从10开始,我们可以传递它而不是0。

&#13;
&#13;
angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.items = [{
      amount: 29.9,
      code: "012",
      currency: "BRL",
      payedDate: "2016-11-10",
      roDate: "2016-08-01",
      type: "OTHER"
    }, {
      amount: 39.9,
      code: "013",
      currency: "BRL",
      payedDate: "2016-11-11",
      roDate: "2016-08-01",
      type: "OTHER",
    }];
    $scope.totalOfSumAmount =   $scope.items.reduce(function(carry, currentItem) {
      //add the amount from the current item to the running total (carry)
      return carry + currentItem.amount;
    }, 0);//0 is the initial value
  });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
Total: <span> {{ totalOfSumAmount }} </span>
  </div>
&#13;
&#13;
&#13;