Javascript - 将if语句转换为switch语句 [英] Javascript - turning if statement into switch statement

查看:127
本文介绍了Javascript - 将if语句转换为switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用javascript将if语句转换为switch语句。这是工作if语句:

  if(!error1(num,a_id)&&!error2(num,b_id )&&!error3(num,c_id)&&!error4(num,d_id)){
a.innerHTML = num;

有关如何将其放入switch语句的任何提示都会很棒。谢谢

解决方案

可以使这个开关,但目前还不清楚你为什么要这样做。乍一看,这不是那种使用 switch for。(/ p)的情况(在一组值中选择并为每个值做一些不同的事情)。 >

这是怎样的,虽然我不推荐它:

  switch(false ){
case!error1(num,a_id):
case!error2(num,b_id):
case!error3(num,c_id):
case!error4(num ,d_id):
//什么都不做
休息;
默认值:
a.innerHTML = num;
休息;
}

这适用于JavaScript,但大多数其他语言<$ c不适用$ C>开关。它起作用的原因是当执行点到达时, case 标签被评估,并且它们是保证按源代码顺序进行评估。所以你要打开值 false ,这将首先进行测试(使用严格相等, === )反对!error1(num,a_id)的返回值,然后如果不匹配,则反对!error2(num,a_id)等;如果它们都不匹配,则它们都评估 true ,并且默认块中的代码运行。


I'm trying to convert an if statement into a switch statement using javascript. This is the working if statement:

      if(!error1(num, a_id) && !error2(num, b_id) && !error3(num, c_id) && !error4(num, d_id)) {
    a.innerHTML = num;

Any tips on how to put this into a switch statement would be great. Thanks

解决方案

You can make this a switch, but it's unclear why you would want to. On first glance, this isn't the kind of situation (selecting amongst a set of values and doing something different for each of them) that you use switch for.

Here's how, though I don't recommend it:

switch (false) {
    case !error1(num, a_id):
    case !error2(num, b_id):
    case !error3(num, c_id):
    case !error4(num, d_id):
        // Do nothing
        break;
    default:
        a.innerHTML = num;
        break;
}

This works in JavaScript, but not in most other languages that have switch. The reason it works is that the case labels are evaluated when the execution point reaches them, and they're guaranteed to be evaluated in source code order. So you're switching on the value false, which will first be tested (using strict equality, ===) against the return value of !error1(num, a_id), and then if that doesn't match, against !error2(num, a_id), etc.; if none of them matches, then they all evaluated true, and the code in the default block runs.

这篇关于Javascript - 将if语句转换为switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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