javascript - 如何在angularjs中为负数和正数求和

标签 javascript jquery css angularjs wordpress

我通过 $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");
}

此函数为我提供了总计,但我需要将负值和正值的总计分开。

提前致谢。

最佳答案

你可以使用 filter reduce 方法,

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/

相关文章:

javascript - 查看未从指令功能更新

javascript - 单击两者时,下一个和上一个按钮不起作用

javascript - 结合 $(this) 和 $ ("li:eq(ui.item.index())")

javascript - 如何在包括标点符号和特殊字符的范围内包装字母?

css - 浏览器告诉 "failed to compile"

css - 如何使用 CSS 根据需要在图像周围绘制边框?

javascript - Google Chrome Web Audio API 实现是否支持 ScriptProcessorNode.bufferSize 零(自动)?

javascript - 在 php 代码中嵌入 javascript

jquery - 如何使用 jQuery 更改 HTML 属性名称?

html - 如何将 .png 图像文件中的前景色从蓝色转换为黑色?