簡體   English   中英

如何在迭代中求和

[英]How to sum values in an iteration

我有數組$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>

最簡單(也是最有效)的方法是編寫一個為您完成此任務的函數。

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

您可以使用Array.prototype.reduce

$scope.totalOfSumAmount = $scope.otherDetailsData.reduce(function(prev, curr) {
  return prev + curr.amount;
}, 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。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM