if/else and if/elseif

后端 未结 10 1858
傲寒
傲寒 2020-12-17 01:00

If I have a statement block like this:

if (/*condition here*/){ }
else{ }

or like this:

if (/*condition here*/)
else if (/         


        
10条回答
  •  离开以前
    2020-12-17 01:32

    Without "elseif" syntax you would have to write chain if-statements for processing one of several possible outcomes this way:

    if( str == "string1" ) {
       //handle first case
    } else {
        if( str == "string2" ) {
           //handle second case
        } else {
           if( str == "string3" ) {
               //handle third case
           } else {
              //default case
           }
        }
     }
    

    instead you can write

    if( str == "string1" ) {
       //handle first case
    } else if( str == "string2" ) {
       //handle second case
    } else if( str == "string3" ) {
       //handle third case
    } else {
       //default case
    }
    

    which is completely the same as the previous one, but looks much nicer and is much easier to read.

提交回复
热议问题