Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am going through codeacademys JavaScript tutorials as i am new to it. The tutorial asks for the following:

Print out the numbers from 1 - 20.
The rules:
- For numbers divisible by 3, print out "Fizz".
- For numbers divisible by 5, print out "Buzz".
- For numbers divisible by both 3 and 5, print out "FizzBuzz" in the console.
- Otherwise, just print out the number.

Here is my code:

for (i=1; i<=20; i++) {

if(i%3==0) {
    console.log("Fizz");
} 
if(i%5==0){
    console.log("Buzz");
}else if (i%5==0 && i%3==0) {
    console.log("fizzBuzz");
} else {
    console.log(i);
}

}

i am getting an error saying that i am printing out the wrong number of items, anyone know why that is?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
209 views
Welcome To Ask or Share your Answers For Others

1 Answer

The check for both 3 and 5 must be first, otherwise the two other statements are true already and give separate logs. Now you print FizzBuzz in a single console.log statement.

   for (i=1; i<=20; i++) {

      if (i%5==0 && i%3==0) {
          console.log("FizzBuzz");
      } else if(i%3==0) {
          console.log("Fizz");
      } else if(i%5==0){
          console.log("Buzz");
      } else {
          console.log(i);
      }

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...