Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
25
rated 0 times [  28] [ 3]  / answers: 1 / hits: 42800  / 10 Years ago, wed, november 12, 2014, 12:00:00

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.



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.


More From » loops

 Answers
16

You're not actually executing the function. You need to call 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);

[#68827] Sunday, November 9, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
angelicajayleneh

Total Points: 216
Total Questions: 110
Total Answers: 100

Location: Sudan
Member since Tue, Aug 3, 2021
3 Years ago
;