我通过 $http.get 方法从服务器获取 json 数据。在名为 Credits 的字段之一的数据中,它包含负值和正数。任何人都可以帮助我如何在单独的总计中得到负数和在单独的总计中得到正数??
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");
}
此函数为我提供了总计,但我需要将负值和正值的总计分开。
提前致谢。
最佳答案
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);
关于javascript - 如何在angularjs中为负数和正数求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46752736/