简体   繁体   English

为什么我的if / else语句不能正常工作?

[英]Why doesn't my if / else statement work properly?

I am trying to iterate through the arrays in the numbers variable, and if a number can be divided by 3 I'm logging "fizz", if it can be divided by 5 I'm logging "buzz", and if a number can be divided by 3 + 5, or 15, I'm logging "fizzbuzz" 我正在尝试遍历numbers变量中的数组,如果一个数字可以除以3,我正在记录“嘶嘶声”,如果可以将其除以5,则我正在记录“嗡嗡声”,如果一个数字可以除以3 + 5或15,我正在记录“ fizzbuzz”

Here is the working code: 这是工作代码:

var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for (var i = 1; i <= numbers.length; i++) {  
    if (i % 15 === 0) {
        console.log("FizzBuzz");
    } else if (i % 5 === 0) {
        console.log("Buzz");
    } else if (i % 3 === 0) {
        console.log("Fizz");
    } else {
        console.log(i);
    }
};

Here is my original code, which doesn't log "fizzbuzz" 这是我的原始代码,不记录“ fizzbuzz”

var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for (var i = 1; i <= numbers.length; i++) {      
    if (i % 5 === 0) {
        console.log("Buzz");
    } else if (i % 3 === 0) {
        console.log("Fizz");
    } else if (i % 15 === 0) {
        console.log("FizzBuzz");
    } else {
        console.log(i);
    }
};

Why does the (i % 15 === 0) condition need to precede the other two conditions? 为什么(i%15 === 0)条件需要先于其他两个条件? Shouldn't it not matter? 没关系吗?

The number 15 is divisible by both 3 and 5. If you don't test it first, then you'll never get there. 数字15可被3和5整除。如果不先进行测试,就永远不会到达那里。

So let's take 30 as an example. 让我们以30为例。 If you check 15 first, you'll see that it's divisible by 15. However, if you check either 5 or 3 first, it'll be flagged as being divisible by either of those. 如果先检查15,则将其除以15。但是,如果先检查5或3,则将其标记为可被其中任何一个除。

After one of your conditions evaluates as true, you break out of that if-block and don't evaluate following else-if/else statements. 在您的条件之一评估为真之后,您便会突破该if块,并且不遵循else-if / else语句进行评估。 If you want the rest of them to evaluate you can make them if statements instead of else-if's. 如果您想让其他人评估,则可以使用if语句代替else-if语句。

It's because firstly the computer checks for the first statement and then the others as you use the ELSE IF which means, to check the statement after the first one is false. 这是因为首先计算机检查第一个语句,然后在您使用ELSE IF时检查其他语句,这意味着在第一个语句为假之后检查该语句。 Use IF for all instead. 请全部使用IF。

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

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