我正在尝试获取一个数字数组,并记录什么数字是模数2,余数为0 i % 2 === 0
。对于模数为2且余数为1的数字i % 2 === 1
,我想将这些数字推入数组(似乎最适合记录一组数字)。
从那里,我将返回存在的数字的sumTotal,%2 === 0
并打印出数组中的数字%2 === 1
。
下面的问题适用于,if statement
但是当我添加时,我else if
很难弄清楚如何将项目推入else if语句的数组中。
var numSet = [1, 4, 6, 450, 5, 222, 397, 962, 678, 222, 459];
var myFunc = function (num) {
var total = 0;
var total2 = [];
for (var i = 0; i < num.length; i += 1) {
if (num[i] % 2 === 0) {
total += num[i];
} else if (num[i] % 2 === 1) {
total2[num[i]] = num[i].push;
console.log(total2);
}
}
return 'The total is ' + total + ' and the remainder is ' + total2;
};
代码的问题在于,您可以total2
像这样将新值推入
total2.push(num[i]);
但是您可以像这样使用Array.filter
和Array.reduce
var numSet = [1, 4, 6, 450, 5, 222, 397, 962, 678, 222, 459];
var oddNumbers = numSet.filter(function(currentNumber) {
return currentNumber % 2 === 1;
});
var total = numSet.reduce(function (total, currentNumber) {
if (currentNumber % 2 === 0) {
total += currentNumber;
}
return total;
}, 0);
console.log(total, oddNumbers);
输出
2544 [ 1, 5, 397, 459 ]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句