Why Print FizzBuzz Instead of 1?


#1

Hi,
this is my code:

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

for (i = 0; i < numbers.length; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log([i]);}
}

It seems fine, but it prints FizzBuzz instead of one. (The array is not a problem, I've tried my code without var numbers. I got the same outcome.)

Could someone please help?


#2

@betaslayer24635,
Either you use

for (var i = 1; i < 21; i++) {
   if (i % 3 === 0 && i % 5 === 0) {
         console.log("FizzBuzz");
   } else if (i % 3 === 0) {
         console.log("Fizz");
   } else if (i % 5 === 0) {
         console.log("Buzz");
   } else {
         console.log(i);
   }
}

or you use

var numbers = 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

for (var i = 0; i < numbers.length; i++) {
   if (numbers[i] % 3 === 0 && numbers[i] % 5 === 0) {
        console.log("FizzBuzz");
   } else if (numbers[i] % 3 === 0) {
        console.log("Fizz");
   } else if (numbers[i] % 5 === 0) {
        console.log("Buzz");
   } else {
        console.log(numbers[i]);
   }
}

#3

Thank you, it worked.


#4

The problem seems to be that you don't use the numbers array for anything else then its length method. So you're not starting at 1 but 0 which fulfills the FizzBuzz conditions. Also why do you print i in an array for the else case? And why didn't you declare i with a var on first use?