有人可以帮助我如何在javascript中总计/收集正数和负数吗?我使用什么方法
答案 0 :(得分:0)
某些有用的方法可能是 filter
和 reduce ,假设您引用的是要累加的一组数字[sic] (我认为您的意思是总和):
const nums = [5, 3, -2, 0, 9, -8, 7]
positive_nums_total = nums.filter(num => num > 0).reduce((a, b) => a + b, 0)
negative_nums_total = nums.filter(num => num < 0).reduce((a, b) => a + b, 0)
overall_total = nums.reduce((a, b) => a + b, 0)
console.log(`nums array: ${JSON.stringify(nums)}`)
console.log(`Postive number total: ${positive_nums_total}`)
console.log(`Negative numbers total: ${negative_nums_total}`)
console.log(`Overall total: ${overall_total}`)