简体   繁体   中英

Logical Operators in Javascript

I want to print out FizzBuzz when i is both divisible by 3 and by 5. What could be the problem with my code?

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

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

If the first or second condition is true, it enters that block, but doesn't evaluate any of the other else if conditions. Because the third condition requires both the first and second to be true, there's no way it will ever enter that block.

Try arranging your conditions like this:

for(var i = 1; i<=20; 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);
     }
}

But just for fun, here's a much more compact version that abuses the conditional operator :

for(var i = 1; i<=20; i++){
    console.log(i % 15 ? i % 5 ? i % 3 ? i : "Fizz" : "Buzz" : "FizzBuzz");
}

The main issue is that your check for "FizzBuzz" doesn't happen until after your other comparisons. If i % 3 === 0 (one of the requirements to print "FizzBuzz"), it will never reach the FizzBuzz check.

As a simple fix, move your FizzBuzz check to the first if-statement.

for(var i = 1; i <= 20; i++) {
     if(i % 3 === 0 && i % 5 === 0) {
         console.log("FizzBuzz");
     }
     else if(i % 5 === 0) {
         console.log("Buzz");
     }
     else if(i % 3 === 0) {
         console.log("FizzBuzz");
     }
     else {
         console.log(i);
     }
}

As another thing to think about, if i is divisible by both 3 and 5, then it is divisible by their least-common denominator, yes? The least common denominator (the smallest whole number that is divisible by a group of numbers) of 3 and 5 is 15, so you could replace...

if(i % 3 === 0 && i % 5 === 0) {

...with...

if(i % 15 === 0) {

(i%3 ==0 && i%5 ==0) should be the first condition. If you think about it, if i is divisible by 3 and by 5 it will enter the first if statement before it reaches the third.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM