Here is the code :
var i = 0;
for (i = 1; i <= 20; i++) {
if (i % 5 === 0 && i % 3 === 0) {
console.log("FizzBuzz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else {
console.log(i);
}
}
and this is the output :
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
The code is ok and works well but I don't understand why does it only print FizzBuzz
when logical operator && is in if
statement and not in else if
?
Once one of the conditions in the if (...)
/ else if (...)
is true
(from top to bottom), the rest of the conditions are not evaluated and the program goes into the next loop (next i
) value.
If you swap the order:
var i = 0;
for (i = 1; i <= 20; i++) {
if (i % 5 === 0) {
// This evaluates to true for a number that is multiple of 5 and 3, and it prints "Buzz", and goes into the next loop.
console.log("Buzz");
} else if (i % 5 === 0 && i % 3 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else {
console.log(i);
}
}
If you are looking for a shorter version of FizzBuzz, here's an interesting answer by Paul Irish (added more brackets for clarity):
for (var i = 1; i <= 100; i++) {
var f = i % 3 == 0, b = i % 5 == 0;
console.log(f ? (b ? "FizzBuzz" : "Fizz") : (b ? "Buzz" : i));
}
Source: https://gist.github.com/jaysonrowe/1592432#gistcomment-790724
This is correct way with else if statement:
for(i = 1; i <= 100; 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);
}
}
Another solution with switch statement:
for(i = 1; i <= 100; i++){
switch (true) {
case (i % 3 === 0 && i % 5 === 0) :
console.log('FizzBuzz');
break;
case (i % 3 == 0) :
console.log('Fizz');
break;
case (i % 5 == 0) :
console.log('Buzz');
break;
default:
console.log(i);
break;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.