programming-languages - if/else 和 if/elseif

标签 programming-languages syntax if-statement

如果我有这样的语句块:

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/

相关文章:

excel - 将word文档解析成excel文件

c - 一种不使用 'C' 的语言?

python - 为什么 (1 in [1,0] == True) 评估为 False?

java - Groovy 语法是 Java 语法的精确超集吗?

vb.net - 简单如果检查多个值vb

c++ - 什么时候执行类型参数的类型检查?

scala - Lisp是REPL唯一的语言吗?

python - 使用 Python 语法的子集加速编写 C 程序

javascript - 在条件语句中提升函数

java - 涉及二维数组值的if语句java