2017-10-15 53 views
0

我通过$ http.get方法从服务器获取json数据。在名为Credits的数据之一中,它包含负值和正数。任何人都可以帮助我如何获得单独总计中的单独总数和正数中的负数?如何在angularjs中对负数和正数进行求和

Array.prototype.sum = function (prop) { 
    var total = 0 
    for (var i = 0, _len = this.length; i < _len; i++) { 
     total += parseInt(this[i][prop]) 
    } 
    return total 
} 
$scope.totalCreadit = function (arr) { 
    return arr.sum("credits"); 
} 

这个函数给我的总数,但我需要总共分离负值和正值。

在此先感谢。

+0

你要什么'totalCreadit'在这种情况下返回? – dfsq

+0

只是想知道该功能如何工作。这里没有定义'arr' – brk

回答

0

你可以使用filterreduce方法,

var arr = [ 1, 2, 3, 4, 5, -2, 23, -1, -13, 10, -52 ], 
 
    positive = arr.filter(function (a) { return a >= 0; }), 
 
    negative = arr.filter(function (a) { return a < 0; }), 
 
    sumnegative = negative.reduce(function (a, b) { return a + b; }), 
 
    sumpositive = positive.reduce(function (a, b) { return a + b; }); 
 
console.log(sumnegative); 
 
console.log(sumpositive);

相关问题