【问题标题】:How to make sum for negative number and positive numbers in angularjs如何在angularjs中为负数和正数求和
【发布时间】:2017-10-15 07:29:37
【问题描述】:

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

这个函数给了我总数,但我需要将负值和正值分开。

提前致谢。

【问题讨论】:

  • 在这种情况下你想让totalCreadit返回什么?
  • 只是想知道这个函数是怎么工作的。这里arr没有定义

标签: javascript jquery css angularjs wordpress


【解决方案1】:

您可以使用 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 2013-04-21
    • 2014-08-31
    • 1970-01-01
    相关资源
    最近更新 更多