为什么 Javascript `if...else if` 不以 `else` 结尾?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8060529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:07:47  来源:igfitidea点击:

Why would Javascript `if...else if` not end with an `else`?

javascriptif-statementconditional

提问by Starkemp315

Here is a snippet of JavaScript code from a tutorial I was working with. I don't understand why it doesn't end with a final elseclause; I thought that was a rule.

这是我正在使用的教程中的一段 JavaScript 代码。我不明白为什么它不以最后一个else条款结束;我以为这是规则。

var curScene = 0;

function changeScene(decision) {
  var message = "";

  if(curScene == 1) {
    message = " welcome";
  } else if (curScene == 2) {
    message = " this is scene two";
  } else if (curScene == 3) {
    message = " this is scene three";
  }

  document.getElementById("sceneimg").src = "scene" + curScene + ".png";

  if(message != ""){
    alert(message);
  }
}

回答by Thilo

I thought it was always supposed to end with an "else"?

我认为它总是应该以“else”结尾?

The elseblock is optional. You can have ifwithout else.

else块是可选的。你可以if没有else

回答by Petar Ivanov

For the same reason as why you can have just a single if:

出于相同的原因,如果您只能拥有一个:

if( /*condition*/ ) {
    //some code
}

//other stuff

回答by Wazy

Consider 3 Scenario
Scenario 1:Boolean condition

考虑 3 场景
场景 1:布尔条件

if (condition) {}
else {}

Specifying a condition as else if would be redundant, and it's really obvious to the reader what the code does. There is no argument for using else if in this case.

将条件指定为 else if 将是多余的,而且代码的作用对读者来说非常明显。在这种情况下,没有理由使用 else if。

Scenario 2:Infinite states

场景 2:无限状态

Here we are interested in testing for conditions A and B (and so on), and we may or may not be interested in what happens if none of them holds:

在这里,我们对测试条件 A 和 B(等等)感兴趣,我们可能对如果它们都不成立会发生什么感兴趣,也可能不感兴趣:

if (conditionA) {}
else if (conditionB) {}
else {} // this might be missing as it is in your case

The important point here is that there isn't a finite number of mutually-exclusive states, for example: conditionA might be num % 2 == 0and conditionB might be num % 3 == 0.

这里的重点是没有有限数量的互斥状态,例如:conditionA 可能是num % 2 == 0,conditionB 可能是num % 3 == 0

I think it's natural and desirable to use a reasonable amount of branches here; if the branches become too many this might be an indication that some judicious use of OO design would result in great maintainability improvements.

我认为在这里使用合理数量的分支是自然和可取的;如果分支变得太多,这可能表明对 OO 设计的一些明智使用将导致极大的可维护性改进。

Scenario 3:Finite states

场景3:Finite states

This is the middle ground between the first two cases: the number of states is finite but more than two. Testing for the values of an enum-like type is the archetypal example:

这是前两种情况之间的中间地带:状态的数量是有限的,但多于两个。测试类枚举类型的值是原型示例:

if (var == CONSTANT_FOO) {}
else if (var == CONSTANT_BAR) {} // either this,
else {} // or this might be missing

In such cases using a switch is probably better because it immediately communicates to the reader that the number of states is finite and gives a strong hint as to where a list of all possible states might be found (in this example, constants starting with CONSTANT_). My personal criteria is the number of states I 'm testing against: if it's only one (no else if) I 'll use an if; otherwise, a switch. In any case, I won't write an else if in this scenario.

在这种情况下,使用 switch 可能更好,因为它会立即向读者传达状态的数量是有限的,并给出了一个关于在哪里可以找到所有可能状态的列表的强烈提示(在这个例子中,常量以 CONSTANT_ 开头) . 我的个人标准是我要测试的状态数:如果只有一个(没有其他 if),我将使用 if;否则,一个开关。无论如何,在这种情况下,我不会写 else if。

Adding else as an empty catch-errors block

添加 else 作为一个空的 catch-error 块

This is directly related to scenario #2 above. Unless the possible states are finite and known at compile time, you can't say that "in any other case" means that an error occurred. Seeing as in scenario #2 a switch would feel more natural, I feel that using else this way has a bad code smell.

这与上面的场景#2 直接相关。除非可能的状态是有限的并且在编译时已知,否则您不能说“在任何其他情况下”意味着发生了错误。看到在场景 #2 中切换会感觉更自然,我觉得以这种方式使用 else 会产生不好的代码味道。

Use a switch with a default branch instead. It will communicate your intent much more clearly:

改用带有默认分支的开关。它将更清楚地传达您的意图:

switch(direction) {
    case 'up': break;
    case 'down': break;
    default: // put error handling here if you want
}

This might be a bit more verbose, but it's clear to the reader how the code is expected to function. In my opinion, an empty else block would look unnatural and puzzling here.

这可能有点冗长,但读者很清楚代码的预期功能。在我看来,一个空的 else 块在这里看起来不自然且令人费解。

回答by Niet the Dark Absol

It doesn't have to, for the same reason an ifon its own doesn't require an else.

它没有必要,出于同样的原因, anif本身不需要else.

Usually it's a good idea to have one, as a sort of "catch-all" situation, but the above code could be written as:

通常有一个是个好主意,作为一种“包罗万象”的情况,但上面的代码可以写成:

switch(curScene) {
    case 1: message = " welcome"; break;
    case 2: message = " this is scene two"; break;
    case 3: message = " this is scene three"; break;
}

In the above code, I could also add:

在上面的代码中,我还可以添加:

    default: message = " invalid curScene value"; break;

But it's completely optional to do so. It depends on how reliable the curScenevariable is whether or not I personally would add it in.

但这样做完全是可选的。这取决于curScene我个人是否会添加变量的可靠性。

回答by linuxdan

Not having an else clause is fine syntactically. MDN DocumentationBasically the second if becomes the body of the else, see the section on "how it would look like if the nesting were properly indented".

没有 else 子句在语法上很好。MDN 文档基本上第二个 if 成为 else 的主体,请参阅“如果嵌套正确缩进会是什么样子”一节。

As to whether it's bad practice I think that depends on intent. By not explicitly defining the final else clause, you might end up with a bug where a condition you didn't cover comes through. Consider this:

至于这是否是不好的做法,我认为这取决于意图。如果没有明确定义最后的 else 子句,您可能最终会遇到一个错误,其中出现了您没有涵盖的条件。考虑一下:

if(myVariable > 0) {
   doSomething();
} else if(myVariable < 0) {
   doSomethingElse();
}

Nothing happens if myVariable is 0. It would be hard to see if you were just glancing through the code. I would say if you run into this pattern it would be a code smell, something might be wrong, but it could be fine.

如果 myVariable 为 0,则什么都不会发生。如果您只是浏览一下代码,将很难看出。我会说,如果您遇到这种模式,那将是一种代码异味,可能有问题,但可能没问题。

The same logic could always be expressed with nested if statements. I would go with whatever is more readable.

相同的逻辑总是可以用嵌套的 if 语句来表达。我会选择任何更具可读性的东西。

回答by Serdalis

elseis a default casefor the ifstatement. If there is no elsethen if none of the conditions in the ifor else ifcases are met than the ifstatment will do nothing.

else是一个default caseforif语句。如果没有,else那么如果ifelse if案例中的任何条件都不满足,则该if语句将不执行任何操作。

Usually it is good practice to have a default case but there are a lot of times where it is not necessary and thus excluded from the code.

通常有一个默认情况是一种很好的做法,但很多时候它是没有必要的,因此被排除在代码之外。

In this case, if the curScenewas anything other than 1, 2, 3then the elsestatment would be used, but since there is no processing to be done on other cases the coder has not included an else.

在这种情况下,如果curScene是除此之外的任何内容,1, 2, 3则将使用该else语句,但由于没有对其他情况进行处理,因此编码器未包含else.

回答by James.Xu

yes, always have a elseis VERY GOODhabit(when using with if-elseif). sometimes people might even write this:

是的,总是有一个else非常好的习惯(当与 if-elseif 一起使用时)。有时人们甚至可能会这样写:

if(curScene == 1) {
    message =" welcome";
else if (curScene == 2) {
    message = " this is scene two";
}
else if (curScene == 3) {
    message = " this is scene three";
} else {
    // empty.
}

to tell people there is indeed nothing to do in the else.

告诉人们在 else 中确实无事可做。

回答by Nagendra

change the if condition for answer validation if(answer==100) to if(answer===100) it is working fine now...

将答案验证的 if 条件 if(answer==100) 更改为 if(answer===100) 现在工作正常...