Javascript 遍历数组,返回奇数和偶数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26896487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
loop through array, returns odd and even numbers
提问by Trace
I am teaching myself code and am trying to solve this problem:
我正在自学代码并试图解决这个问题:
Write a loop that loops through nums, if the item is even, it adds it to the evens array, if the item is odd, it adds it to the odds array.
编写一个循环遍历 nums 的循环,如果项目是偶数,则将其添加到 evens 数组中,如果项目是奇数,则将其添加到odds 数组中。
This is what I have so far:
这是我到目前为止:
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);
They don't return anything and I'm not sure where I'm going wrong, any help would be much appreciated.
他们不返回任何东西,我不确定我哪里出错了,任何帮助将不胜感激。
回答by Casey Rule
You're not actually executing the function. You need to call evenNumbers();
您实际上并未执行该功能。你需要调用 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);
回答by liron_hazan
I would recommend checking out the array.prototype.filter function with ES6 syntax:
我建议使用 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);
So elegant :)
好优雅:)
回答by Kyle
You aren't actually calling your function, just defining it.
你实际上并不是在调用你的函数,只是定义了它。
call:
称呼:
evenNumbers(nums);
before alerting the arrays
在提醒阵列之前
回答by Trace
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);
回答by sunilsingh
//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`);
}
});
回答by Hyman WS
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();

