switch statement to compare values greater or less than a number

柔情痞子 提交于 2019-12-31 17:25:20

问题


I want to use the switch statement in some simple code i'm writing.

I'm trying to compare the variable in the parenthesis with values either < 13 or >= 13.

Is this possible using Switch?

var age = prompt("Enter you age");
switch (age) {
    case <13:
        alert("You must be 13 or older to play");
        break;
    case >=13:
        alert("You are old enough to play");
        break;
}

回答1:


Directly it's not possible but indirectly you can do this

Try like this

switch (true) {
    case (age < 13):
        alert("You must be 13 or older to play");
        break;
    case (age >= 13):
        alert("You are old enough to play");
        break;
}

Here switch will always try to find true value. the case which will return first true it'll switch to that.

Suppose if age is less then 13 that's means that case will have true then it'll switch to that case.




回答2:


Instead of switch you can easily to the same thing if else right?

if(age<13)
    alert("You must be 13 or older to play");
else
    alert("You are old enough to play");



回答3:


Instead of switch use nested if else like this:

if (x > 10) {
    disp ('x is greater than 10') 
}
elseif (x < 10){
    disp ('x is less than 10')
}
else
{
    disp ('error')
}


来源:https://stackoverflow.com/questions/32576618/switch-statement-to-compare-values-greater-or-less-than-a-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!