总结 angular.foreach 循环的数量

summing up number of angular.foreach loop

我正在尝试总结一些应该是简单函数的数字。我遍历了我的数字列表,可以从日志中看到我看到的每个数字。

然后我有以下内容,其中我有一个保存总和的 var,应该 return 它。

但是没有任何反应!

代码如下:

  angular.extend(self, {

    getTotalGood : function(){
      var total = 1;
      angular.forEach( self.myproducts, function( value, key ){
        console.log(key + ' : ' + value.product.cost);
        total = value.product.cost;
      })
      return total;
    }

  })

  self.getTotalGood();

改变你的方法如下:

 getTotalGood : function(){
  var total = 0;
  angular.forEach( self.myproducts, function( value, key ){
    console.log(key + ' : ' + value.product.cost);
    total += value.product.cost;
  })
  console.log("total: " + total);
  return total;
}