简体   繁体   English

Javascript中的逻辑运算符

[英]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? 我想同时被3和5整除时打印出FizzBu​​zz。我的代码可能是什么问题?

 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. 如果第一个或第二个条件为true,则它将进入该块,但else if条件满足,则不评估其他else if条件。 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. 主要问题在于,只有在进行其他比较之后,您才可以检查“ FizzBu​​zz”。 If i % 3 === 0 (one of the requirements to print "FizzBuzz"), it will never reach the FizzBuzz check. 如果i % 3 === 0 (打印“ FizzBu​​zz”的要求之一),它将永远不会达到 FizzBu​​zz检查。

As a simple fix, move your FizzBuzz check to the first if-statement. 作为一个简单的解决方法,将FizzBu​​zz检查移至第一个if语句。

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? 还要考虑的另一件事是,如果i被3和5整除,那么它可以被它们的最小公分母整除,是吗? 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... 3和5的最小公分母(可被一组数字整除的最小整数)是15,因此可以替换...

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

...with... ...与...

if(i % 15 === 0) {

(i%3 ==0 && i%5 ==0) should be the first condition. (i%3 ==0 && i%5 ==0)应该是第一个条件。 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. 如果您考虑一下,如果我被3和5整除,它将在到达第三个if语句之前输入第一个if语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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