3 回答
TA贡献1799条经验 获得超8个赞
您可以使用 非常简单地完成此操作Array#reduce。
const list=[22,45,63,223,12,56,89];
let evenSum = list.reduce((acc,curr)=>acc + (curr % 2 == 0 ? curr : 0), 0);
console.log('Even sum:', evenSum);
let oddSum = list.reduce((acc,curr)=>acc + (curr % 2 == 1 ? curr : 0), 0);
console.log('Odd sum:', oddSum);
如果性能特别重要,您可以通过一次reduce操作计算两个总和。
const list=[22,45,63,223,12,56,89];
let [evenSum, oddSum] = list.reduce((acc,curr)=>(acc[curr % 2] += curr, acc), [0, 0]);
console.log('Even sum:', evenSum);
console.log('Odd sum:', oddSum);
TA贡献1829条经验 获得超7个赞
let list = [22,45,63,223,12,56,89];
let number = 0, rest = 0, result = 0;
for(let counter = 0; counter < 20; counter += 1) {
number = list[counter];
rest = number%2;
if(rest == 0) {
result += number; //here
}
}
console.log(result); //printing result
TA贡献1813条经验 获得超2个赞
从技术上讲,您可以循环遍历数组,如果均匀,则将其添加到变量中,否则将其添加到不同的变量中。
list = [22, 45, 63, 223, 12, 56, 89]
evensum = 0;
oddsum = 0;
list.forEach(function(e) {
if (e % 2 == 0) {
evensum += e;
} else{
oddsum += e;
}
});
console.log(evensum, oddsum)
添加回答
举报