JavaScript 中的“elseif”语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4005614/
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
"elseif" syntax in JavaScript
提问by Hari Gillala
Is this correct?
这样对吗?
if(condition)
{
}
elseif(condition)
{
}
else
{
}
回答by Jeff
JavaScript's elseif is in the format "else if", e.g.:
JavaScript 的 elseif 格式为“else if”,例如:
if (condition) {
} else if (other_condition) {
} else {
}
回答by jMyles
Just add a space:
只需添加一个空格:
if (...) {
} else if (...) {
} else {
}
回答by Tamlyn
You could use this syntax which is functionally equivalent:
您可以使用此功能等效的语法:
switch (true) {
case condition1:
//e.g. if (condition1 === true)
break;
case condition2:
//e.g. elseif (condition2 === true)
break;
default:
//e.g. else
}
This works because each condition
is fully evaluated before comparison with the switch
value, so the first one that evaluates to true
will match and its branch will execute. Subsequent branches will not execute, provided you remember to use break
.
这是有效的,因为condition
在与switch
值比较之前每个都被完全评估,所以评估为的第一个true
将匹配并且其分支将执行。后续分支将不会执行,前提是您记得使用break
.
Note that strictcomparison is used, so a branch whose condition
is merely "truthy" will notbe executed. You can cast a truthy value to true
with double negation: !!condition
.
请注意,使用了严格比较,因此不会执行condition
仅“真实”的分支。您可以使用双重否定将真实值转换为:。true
!!condition
回答by skube
Actually, technicallywhen indented properly, it would be:
实际上,从技术上讲,正确缩进时,它将是:
if (condition) {
...
} else {
if (condition) {
...
} else {
...
}
}
There is no else if
, strictly speaking.
else if
严格来说,没有。
(Update: Of course, as pointed out, the above is notconsidered good style.)
(更新:当然,正如所指出的,以上不被认为是好的风格。)
回答by IdemeNaHavaj
if ( 100 < 500 ) {
//any action
}
else if ( 100 > 500 ){
//any another action
}
Easy, use space
简单,使用空间
回答by A.A Noman
Conditional statements are used to perform different actions based on different conditions.
条件语句用于根据不同的条件执行不同的操作。
Use if
to specify a block of code to be executed, if a specified condition is true
使用if
指定的代码块将被执行,如果一个指定的条件是真
Use else
to specify a block of code to be executed, if the same condition is false
使用else
指定的代码块将被执行,如果相同的条件为假
Use else if
to specify a new condition to test, if the first condition is false
使用else if
指定一个新的条件测试,如果第一个条件为假
回答by zloctb
x = 10;
if(x > 100 ) console.log('over 100')
else if (x > 90 ) console.log('over 90')
else if (x > 50 ) console.log('over 50')
else if (x > 9 ) console.log('over 9')
else console.log('lower 9')
回答by codemirror
You are missing a space between else
and if
你在else
和之间缺少一个空格if
It should be else if
instead of elseif
它应该else if
代替elseif
if(condition)
{
}
else if(condition)
{
}
else
{
}