数组中所有正数的和(用 JavaScript 编写)
问题
我们需要编写一个 JavaScript 函数,该函数接受一个数字数组(正数和负数)。我们的函数应计算并返回数组中所有正数的和。
示例
以下是代码 −
const arr = [5, -5, -3, -5, -7, -8, 1, 9]; const sumPositives = (arr = []) => { const isPositive = num => typeof num === 'number' && num > 0; const res = arr.reduce((acc, val) => { if(isPositive(val)){ acc += val; }; return acc; }, 0); return res; }; console.log(sumPositives(arr));
Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.
输出
以下是控制台输出 −
15
广告