JavaScript切换与逻辑运算符? [英] JavaScript switch with logical operators?

查看:177
本文介绍了JavaScript切换与逻辑运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for (var count = 1; count < 6; count++) {
    switch (count) {
        case (2):   document.write("hi"); break;     
        case (count > 3):   document.write("bye"); break;    
        case (count >= 4): document.write("lol"); break;
    }
}

因为它没有按我期望的方式工作,不能打印bye和lol,它让我觉得这在JavaScript中是无效的。我试着寻找一些例子来看看人们是否在Google上这样做,我没有看到。这是否有效?或者为什么这不起作用?

Because it's not working the way I expect, not printing bye and lol, it makes me think this is invalid in JavaScript. I tried looking for some examples to see if people do this on Google, and I saw none. So is this valid or not? or Why might this not work?

推荐答案

switch ,将括号中的表达式与特定情况的值进行比较。

When switch is interpreted, the expression in the parentheses is compared to values of the particular cases.

因此,在您的情况下, count 的值将与 2 <的值进行比较/ code>, count> 3 count> = 4 。那是行不通的。虽然您可以重写它并与 true 进行比较以使其正常工作:

So in your case the value of count would be compared to the values of 2, count > 3 and count >= 4. And that won’t work. Although you can rewrite it and compare to true to get it working:

switch (true) {
    case (count == 2):
        document.write("hi");
        break;
    case (count > 3):
        document.write("bye");
        break;
    case (count >= 4):
        document.write("lol");
        break;
}

但这不是切换应该被使用。

使用 if 语句:

if (count == 2) {
    document.write("hi");
} else if (count > 3) {
    document.write("bye");
} else if (count >= 4) {
    document.write("lol");
}






编辑由于您只使用开关个案(如果案例匹配则中断),我的开关 -to- if / else 翻译是否正确。


Edit    Since you use the switch cases exclusively (break if a case matches), my switch-to-if/else translation is correct.

count> = 4 因为 count>所以永远不会应用case / branch 3 对于 count 值大于等于4也是如此。

But the count >= 4 case/branch will never be applied since count > 3 is true (also) for count values greater or equal 4.

To修复此问题(写byelol获取大于或等于4的值),删除最后一个 else 以使最后一个 if 声明独立于前面的声明:

To fix this problem (write "bye" and "lol" for values greater or equal 4), remove the last else to make the last if statement independent from the preceding:

if (count == 2) {
    document.write("hi");
} else if (count > 3) {
    document.write("bye");
}
if (count >= 4) {
    document.write("lol");
}

这篇关于JavaScript切换与逻辑运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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