Javascript conditional switch statement

前端 未结 4 1980
醉酒成梦
醉酒成梦 2020-11-27 15:07

Is there a way to write a conditional switch statement in javascript?

I\'m guessing not, since the following is always going to default:

    var raw         


        
4条回答
  •  隐瞒了意图╮
    2020-11-27 15:23

    Like this:

    var raw_value = 11.0;
    switch(true) {
        case (raw_value > 10.0):
          height = 48;
          width = 36;
          break;
        case (raw_value > 5.0):
          height = 40;
          width = 30;
          break;
        default:
          height = 16;
          width = 12;
    }
    

    The expressions in the case statements will evaluate to true or false, and if that matches the switch condition... voilà. The default acts like an else.

    Bonus: you can invert the whole logic by simply replacing true with false. With if ... else if statements, you'd have to edit every if-clause individually.

提交回复
热议问题