if/else and if/elseif

后端 未结 10 1871
傲寒
傲寒 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

    Many languages have a grammer like this (here: ECMAScript Language Specification, so JavaScript):

    IfStatement :
        if ( Expression ) Statement else Statement
        if ( Expression ) Statement

    Statement :
        Block
        VariableStatement
        EmptyStatement
        ExpressionStatement
        IfStatement
        IterationStatement
        ContinueStatement
        BreakStatement
        ReturnStatement
        WithStatement
        LabelledStatement
        SwitchStatement
        ThrowStatement
        TryStatement

    Block :
        { StatementListopt }

    StatementList :
        Statement
        StatementList Statement

    So the branches of an ifStatement may contain a block of statements (Block) or one of the other statements (other than Block). That means this is valid:

    if (expr)
        someStatement;
    else
        otherStatement;
    

    And as StatementList may just contain a single statement, these examples are equivalent to the previous:

    if (expr) {
        someStatement;
    } else {
        otherStatement;
    }
    
    if (expr)
        someStatement;
    else {
        otherStatement;
    }
    
    if (expr) {
        someStatement;
    } else
        otherStatement;
    

    And when we replace otherStatement by an additional IfStatement, we get this:

    if (expr) {
        someStatement;
    } else
        if (expr) {
            someOtherStatement;
        }
    

    The rest is just code formatting:

    if (expr) {
        someStatement;
    } else if (expr) {
        someOtherStatement;
    }
    

提交回复
热议问题