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

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

javascript - print numbers between 1- 20 using rules

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

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

1 Answer

0 votes
by (71.8m points)

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);
      }

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...