Javascript条件切换语句 [英] Javascript conditional switch statement
问题描述
有没有办法在javascript中编写条件切换语句?
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_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;
}
如果没有,我应该使用什么 - 长if / else语句?
If not, what should I use instead - a long if/else statement?
谢谢:)
推荐答案
在 切换
语句,评估值为将开关
表达式与案例的评估值进行比较。所以这里将 raw_value
(数字)的值与 raw_value>进行比较。 10.0
(比较表达式)和 raw_value> 5.0
(比较表达式)。
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).
因此除非你的一个case表达式产生一个等于 11.0的数字
或者您使用开关
表达式 true
,您将始终获得默认情况。
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;
}
这篇关于Javascript条件切换语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!