print numbers between 1- 20 using rules

后端 未结 10 1857
不思量自难忘°
不思量自难忘° 2020-12-11 09:45

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:

10条回答
  •  旧时难觅i
    2020-12-11 10:27

    When the value is divisible by 3 and not by 5, on the first If statement "Fizz" is printed.

    Then on the second if statement, the last else is hit so the number will also be printed. You will need to change the if(i%5==0) to else if.

    However there will be a problem now when (i%5==0 && i%3==0) as the else if for that will never be hit. You can fix this by putting this as the first comparison and changing the output to FizzBuzz.

    Like this:

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

    Make sure you understand why this fixes your issue before you move on as you will most likely make the same mistake again.

    Add a comment if you would like me to explain clearer if you are struggling to work out why you have gone wrong.

提交回复
热议问题