[英]How to totalize positive and negative numbers
谁能帮助我如何在javascript中汇总/收集正数和负数? 我使用什么方法
一些有用的方法可以是filter
和reduce假设您指的是要汇总的数字数组 [原文如此] (我假设您的意思是总和):
const nums = [5, 3, -2, 0, 9, -8, 7] const positiveNumsTotal = nums.filter(num => num > 0).reduce((a, b) => a + b, 0) const negativeNumsTotal = nums.filter(num => num < 0).reduce((a, b) => a + b, 0) const overallTotal = nums.reduce((a, b) => a + b, 0) console.log(`nums array: ${JSON.stringify(nums)}`) console.log(`Postive number total: ${positiveNumsTotal}`) console.log(`Negative numbers total: ${negativeNumsTotal}`) console.log(`Overall total: ${overallTotal}`)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.