is switch(true) {… valid javascript?

后端 未结 5 1763
暗喜
暗喜 2020-12-31 00:59

I recently came across code where a switch statement seemed reversed with the answer (boolean) in the switch and the expressions in the case. The code ran fine as intended b

5条回答
  •  生来不讨喜
    2020-12-31 01:08

    The syntax of switch statement is:

    SwitchStatement :  
      switch ( Expression ) CaseBlock  
    CaseBlock :  
      { CaseClauses(opt) }  
      { CaseClauses(opt) DefaultClause CaseClauses(opt) }  
    CaseClauses :  
      CaseClause  
      CaseClauses CaseClause  
    CaseClause :  
      case Expression : StatementList(opt)  
    DefaultClause :  
      default : StatementList(opt)
    

    No where it says that switch expression or the case expression has to be a number, string, boolean or anything. true is perfectly acceptable as a switch expression and y < 20 is perfectly acceptable as case expression. Keep in mind that comparison between switch expression and case expressions are made using === operator.

    In the code you posted, the first true case will be executed until break is encountered or the switch block ends.

提交回复
热议问题