if/else和if/elseif

6 syntax programming-languages if-statement

如果我有这样的语句块:

if (/*condition here*/){ }
else{ }
Run Code Online (Sandbox Code Playgroud)

或者像这样:

if (/*condition here*/)
else if (/*condition here*/) {}
else if (/*condition here*/) {}
Run Code Online (Sandbox Code Playgroud)

有什么不同?

似乎使用if/else,如果part为true状态,​​else部分为所有其他可能选项(false).一个else-if对许多条件都有用.这是我的理解,还有什么我应该知道的吗?

sha*_*oth 21

如果没有"elseif"语法,您必须编写链式if语句,以便以这种方式处理以下几种可能结果之一:

if( str == "string1" ) {
   //handle first case
} else {
    if( str == "string2" ) {
       //handle second case
    } else {
       if( str == "string3" ) {
           //handle third case
       } else {
          //default case
       }
    }
 }
Run Code Online (Sandbox Code Playgroud)

相反,你可以写

if( str == "string1" ) {
   //handle first case
} else if( str == "string2" ) {
   //handle second case
} else if( str == "string3" ) {
   //handle third case
} else {
   //default case
}
Run Code Online (Sandbox Code Playgroud)

这与前一个完全相同,但看起来更好,更容易阅读.


Fre*_*els 14

情况a:

if( condition )
{
}
else
{
}
Run Code Online (Sandbox Code Playgroud)

当上述语句中的条件为false时,将始终执行else块中的语句.

情况b:

if( condition )
{
}
else if( condition2 )
{
}
else
{
}
Run Code Online (Sandbox Code Playgroud)

当'condition'为false时,else if块中的语句只会在condition2为true时执行.当condition2为false时,将执行else块中的语句.