Javascript conditional switch statement

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

    In a switch statement, the evaluated value of the switch expression is compared the the evaluated values of the cases. So here the value of raw_value (number) is compared to raw_value > 10.0 (comparison expression) and raw_value > 5.0 (comparison expression).

    So unless one of your case expressions yield a number equal to 11.0 or you use the switch expression true, you will always get the default case.

    Just use a simple if/else instead:

    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;
    }
    

提交回复
热议问题