数组中所有正数的和(用 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

更新于: 2021-04-17

2K+ 浏览次数

启动您的职业生涯

完成课程,获得认证

开始
广告