循环数组,返回奇数和偶数

时间:2014-11-12 21:01:43

标签: javascript loops

我正在自学代码,并试图解决这个问题:

写一个循环遍历nums的循环,如果该项为偶数,则将其添加到evens数组,如果该项为奇数,则将其添加到odds数组。

这是我到目前为止所做的:

var nums = [1,2,34,54,55,34,32,11,19,17,54,66,13];
var evens = [];
var odds = [];

var evenNumbers = function(nums) {
    for (var i = 0; i < nums.length; i++) {

        if ((nums[i] % 2) != 1) {
            evens.push(nums[i]);
                console.log(evens);
        }
        else {
            odds.push(nums[i]);
                console.log(odds);
        }
    }

};

alert(evens);
alert(odds);

他们没有退货,我不知道我哪里出错了,任何帮助都会非常感激。

6 个答案:

答案 0 :(得分:8)

我建议使用ES6语法检查array.prototype.filter函数:

const oddNumbers = [1,2,34,54,55,34,32,11,19,17,54,66,13].filter((number) => number%2!==0);
console.log(oddNumbers);

如此优雅:)

答案 1 :(得分:7)

您实际上并未执行此功能。你需要调用evenNumbers();

var nums = [1,2,34,54,55,34,32,11,19,17,54,66,13];
var evens = [];
var odds = [];

var evenNumbers = function(nums) {
    for (var i = 0; i < nums.length; i++) {

        if ((nums[i] % 2) != 1) {
            evens.push(nums[i]);
                console.log(evens);
        }
        else {
            odds.push(nums[i]);
                console.log(odds);
        }
    }

};

evenNumbers(nums);
alert(evens);
alert(odds);

答案 2 :(得分:1)

你实际上并没有调用你的函数,只是定义它。

呼叫:

evenNumbers(nums);
警告数组之前

答案 3 :(得分:1)

function groupNumbers(arr) {

  var arr = [1,2,3,4,5,6,7,8,9,10];

  var evenNumbers = arr.filter(number => number % 2 == 0);

  console.log("Even numbers " + evenNumbers);

  var oddNumbers = arr.filter(number => number % 2 !== 0);

  console.log("Odd numbers " + oddNumbers);
}

groupNumbers();

答案 4 :(得分:0)

var rsl = {even:[], odd:[]};

[1,2,34,54,55,34,32,11,19,17,54,66,13].forEach(function(val,key,arr)
{
    var wrd = (val % 2) ? 'odd' : 'even';
    rsl[wrd][rsl[wrd].length] = val;
});

console.log(rsl);

答案 5 :(得分:0)

            //Even odd
            var arrays = [1,2,34,54,55,34,32,11,19,17,54,66,13];
            var result = arrays.filter((numbers)=>{
                 if(numbers%2!==0){
                   console.log(`${numbers} is not even`);
                 } else {
                     console.log(`${numbers} is even`);
                }
            });