JavaScript 条件切换语句 [英] JavaScript conditional switch statement

查看:34
本文介绍了JavaScript 条件切换语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 JavaScript 中编写条件 switch 语句?

Is there a way to write a conditional switch statement in JavaScript?

我猜不是,因为以下内容总是default:

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?

谢谢:)

推荐答案

switch 语句,将switch 表达式的计算值与case 的计算值进行比较.因此,这里将 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 的数字,或者您使用 switch 表达式 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.

只需使用一个简单的if/else:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆