只添加奇数或偶数的 JavaScript
我们需要编写一个函数,给定一个数字数组和一个字符串,该字符串可以取两个值之一“奇数”或“偶数”,添加符合该条件的数字。如果没有值符合条件,则应返回 0。
例如,−
console.log(conditionalSum([1, 2, 3, 4, 5], "even")); => 6 console.log(conditionalSum([1, 2, 3, 4, 5], "odd")); => 9 console.log(conditionalSum([13, 88, 12, 44, 99], "even")); => 144 console.log(conditionalSum([], "odd")); => 0
因此,让我们编写此函数的代码,我们将在此处使用 Array.prototype.reduce() 方法 −
示例
const conditionalSum = (arr, condition) => {
const add = (num1, num2) => {
if(condition === 'even' && num2 % 2 === 0){
return num1 + num2;
}
if(condition === 'odd' && num2 % 2 === 1){
return num1 + num2;
};
return num1;
}
return arr.reduce((acc, val) => add(acc, val), 0);
}
console.log(conditionalSum([1, 2, 3, 4, 5], "even"));
console.log(conditionalSum([1, 2, 3, 4, 5], "odd"));
console.log(conditionalSum([13, 88, 12, 44, 99], "even"));
console.log(conditionalSum([], "odd"));输出
控制台中的输出将为 −
6 9 144 0
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP