3 回答

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用 非常簡(jiǎn)單地完成此操作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操作計(jì)算兩個(gè)總和。
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貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
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貢獻(xiàn)1813條經(jīng)驗(yàn) 獲得超2個(gè)贊
從技術(shù)上講,您可以循環(huán)遍歷數(shù)組,如果均勻,則將其添加到變量中,否則將其添加到不同的變量中。
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)
添加回答
舉報(bào)