I'm trying to write a code that randomizes a number (1 - 100), then prints all the odd numbers from 40 to that one. If the number is smaller than 40 it should print all the numbers up to the randomized one.
i.e. if the number is 45, it should print 41, 43, 45. And if it's 5 it should print 1,2,3,4,5.
My code below works until I add the else if statement. When I add this if the number is above 40 it still includes all numbers from 0 to 40? I don't understand why as I thought if statements should go one way or another not both?
Any ideas help on how to solve this, or what i'm doing wrong?
Thanks in advance
function myFunc() {
var x = Math.floor(Math.random() * 100);
var counter = [];
for (var i = 0; i < x; i++) {
if (i > 40 && i % 2 == 1) {
counter.push(i);
} else if (i < 40) {
counter.push(i);
}
}
return counter + ',' + x;
}
console.log(myFunc())
Just add a new variable that checks where to start from. That way you can shorten the conditional in the loop too.
function myFunc() {
var x = Math.floor(Math.random() * 100);
var counter = [];
var start = x >= 40 ? 40 : 0; // new variable
for (var i = start; i < x; i++) {
if (i % 2 === 1) { counter.push(i); }
}
return counter + ',' + x;
}
console.log(myFunc())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With