如果我有这样的语句块:
if (/*condition here*/){ }
else{ }
或者像这样:
if (/*condition here*/)
else if (/*condition here*/) {}
else if (/*condition here*/) {}
有什么不同?
似乎在 if/else 中,if 部分用于 true 状态,else 部分用于所有其他可能的选项(false)。 else-if 对许多条件都有用。这是我的理解,还有什么需要我注意的吗?
最佳答案
如果没有“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
}
}
}
相反,你可以写
if( str == "string1" ) {
//handle first case
} else if( str == "string2" ) {
//handle second case
} else if( str == "string3" ) {
//handle third case
} else {
//default case
}
这与前一个完全相同,但看起来更好,更容易阅读。
关于programming-languages - if/else 和 if/elseif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/637980/