Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Codecademy FizzBuzz app, stuck on step 1

Here's my code for Codecamedy's FizzBuzz lesson

var i;
for ( i = 1; i > 20; i++ ) {
  "hello"
  if ( i % 3 === 0 ) {
    if ( i % 5 === 0 ) {
      "FizzBuzz";
    }
    else {
      "Fizz";
    }
  }
  else if ( i % 5 === 0 ) {
    "Buzz";
  }
 else {
    i;
  }
}

I'm trying to first test whether or not the number (i) is divisible by 3. If it is, I then want to check whether it is also divisible by 5. If both conditions are true, I want it to say "FizzBuzz". If only the first condition is true, it should say "Fizz". Then, after determining that i is not divisible by 3, it should check whether i is divisible by 5 and show "Buzz" if that's the case. Failing all divisibility, it should just show the number.

As I expected... it doesn't work as expected. What terribly embarrassing mistakes have I made?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

First, your loop is not even getting off the ground:

for ( i = 1; i > 20; i++ )

will not iterate even once since the middle condition is initially false. I think you meant:

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

"FizzBuzz";

is just a string literal that JavaScript is ignoring. You need to output this string somehow:

console.log("FizzBuzz");

Also, this block

else {
    i;
  }

is also not doing anything. Did you want to display numbers that were divisible by neither 3 nor 5?

else {
    console.log(i);
  }

And, on a similar note, what is the "hello" at the top loop supposed to do?


On a more positive note, I see you're using strict equality:

if ( i % 5 === 0 )

this is a very, very good habit to be in. The non-strict equality operator == will do all sorts of implicit conversions if you're not careful. Always use strict equality unless you purposefully want these implicit conversions to happen.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...