javascript - 将项目插入数组并在 JavaScript 中返回它们

标签 javascript arrays for-loop

我正在尝试获取一个数字数组并记录哪些数字是模 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.filterArray.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/

相关文章:

javascript - ReactJS 使用 Hooks 和 Redux 的良好实践。我应该在每个组件中使用 useSelector,还是应该通过 props 传递?

mysql - 在循环中将数组值更多列插入到mysql

java - array.remove() 给出 IndexOutOfBoundsException

c - 规则 14.2 for 循环应符合 MISRA C 2012 的格式

javascript - Angular 6 从谷歌地图中删除所有标记

javascript - 当子进程调用父进程时,this.props.xyz 不是一个函数

Javascript - 循环内循环

c - OpenMP 点积和指针

javascript - lightbox2 不安全数据图像

ios - 如何删除数组中重复的对象?