is switch(true) {… valid javascript?

后端 未结 5 1790
暗喜
暗喜 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:15

    It is valid.

    The code

    switch(f0()) {
        case f1(): ..; 
        case f2(): ..;
        default: dflt;
    }
    

    where fX() represents an arbitrary expression (a function invocation is used to show forced evaluation) can be approximately re-written as

    for (;;) { // for "break"
        var _x = f0()
        if (_x === f1()) { .. }
        if (_x === f2()) { .. }
        dflt;
        break;
    }
    

    That is, the expression in the case is evaluated and then compared with the expression in the switch. (This is a sharp divergence from languages like C or Java that require constant values in the case expressions.)

    Of course, the break will "exit the switch" - as opposed to the standard fall-through semantics - and as such, where true is the expression supplied to switch, the posted example is semantically equivalent to the if/else if as shown by aefxx.

提交回复
热议问题