I'm a total beginner and I'm stuck completely on this problem. I'm supposed to use a for loop to traverse an array, pushing odd numbers to the 'odd' array, and evens to the 'even' array.
No numbers are showing up in my arrays when I test the code. I've tried writing it the following two ways:
#1
function pickIt(arr){
var odd=[],even=[];
//coding here
for (i = 0; i < arr.length; i++) {
if (arr[i] % 2 !== 0) {
odd.push();
} else {
even.push();
}
console.log(arr[i]);
}
return [odd,even];
#2
function pickIt(arr){
var odd=[],even=[];
//coding here
for (i = 0; i > 0; i++) {
if (i % 2 !== 0) {
odd.push();
} else {
even.push();
}
}
return [odd,even];
}
I've checked out some of the solutions to the problem and with respect to the code I've got in #2, the most common solution I guess has the for condition written like this:
for (i of arr)
and then in the if else statement it's written:
odd.push(i);
even.push(i);
respectively, but I have no idea how people got there especially concerning the 'for' bit. Can anyone help my brain understand this?
function pickIt(arr){
var odd=[],even=[];
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 !== 0) {
odd.push(arr[i]);
} else {
even.push(arr[i]);
}
}
console.log(odd);
console.log(even);
}
pickIt([10,5,6,3,24,5235,31]);
const odds = [];
const evens = [];
function separateOddEven(arr){
for (let i = 0; i < arr.length; i++){
updateArray(arr[i]);
}
}
function updateArray(number){
if (number % 2) {
odds.push(number);
}
else {
evens.push(number);
}
}
separateOddEven([7, 3, 4, 1, 5]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.