javascript 用于比较大于或小于数字的值的 switch 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32576618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
switch statement to compare values greater or less than a number
提问by CP Creative Studio
I want to use the switch
statement in some simple code i'm writing.
我想switch
在我正在编写的一些简单代码中使用该语句。
I'm trying to compare the variable in the parenthesis with values either < 13
or >= 13
.
我正在尝试将括号中的变量与值< 13
或>= 13
.
Is this possible using Switch
?
这可以使用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;
}
回答by Anik Islam Abhi
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.
在这里 switch 将始终尝试找到真正的值。将首先返回 true 的情况它将切换到那个。
Suppose if age is less then 13 that's means that case will have true then it'll switch to that case.
假设如果年龄小于 13,这意味着该案例将为真,然后它将切换到该案例。
回答by Manikanta Reddy
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");
回答by abhi
Instead of switch
use nested if else
like this:
而不是像这样switch
使用嵌套if else
:
if (x > 10) {
disp ('x is greater than 10')
}
else if (x < 10){
disp ('x is less than 10')
}
else
{
disp ('error')
}