我正在尝试获取一个数字数组并记录哪些数字是模 2 且余数为 0 i % 2 === 0
。对于模 2 余数为 1 i % 2 === 1
的数字,我想将这些数字推送到一个数组(似乎最适合记录一组数字)。
从那里我将返回 %2 === 0
数字的总和,并打印数组中的哪些数字是 %2 === 1
。
下面的问题适用于 if 语句
,但是当我添加 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 ]
关于javascript - 将项目插入数组并在 JavaScript 中返回它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20821778/