“elseif” syntax in JavaScript

后端 未结 8 937
刺人心
刺人心 2020-11-29 17:59

How can I achieve an elseif in a JavaScript condition?

8条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 18:20

    You could use this syntax which is functionally equivalent:

    switch (true) {
      case condition1:
         //e.g. if (condition1 === true)
         break;
      case condition2:
         //e.g. elseif (condition2 === true)
         break;
      default:
         //e.g. else
    }
    

    This works because each condition is fully evaluated before comparison with the switch value, so the first one that evaluates to true will match and its branch will execute. Subsequent branches will not execute, provided you remember to use break.

    Note that strict comparison is used, so a branch whose condition is merely "truthy" will not be executed. You can cast a truthy value to true with double negation: !!condition.

提交回复
热议问题