Javascript conditional switch statement

前端 未结 4 1972
醉酒成梦
醉酒成梦 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:42

    No, the switch statement does not work used like that. However, this statement is not always simpler. For example, the switch version takes 15 lines:

    var raw_value = 11.0;
    switch(raw_value) {
        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;
          break;
    }
    

    and the "long" if/else version only 11:

    var raw_value = 11.0;
    if (raw_value > 10.0) {
          height = 48;
          width = 36;
    } else if (raw_value > 5.0) {
          height = 40;
          width = 30;
    } else {
          height = 16;
          width = 12;
    }
    

    So in your case, it is better to use the second one than the first...

提交回复
热议问题