带有逻辑运算符的 JavaScript 开关?

2022-01-19 00:00:00 switch-statement 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;
    }
}

因为它没有按我预期的方式工作,没有打印再见和大声笑,这让我觉得这在 JavaScript 中是无效的.我试着寻找一些例子来看看人们是否在谷歌上这样做,但我没有看到.那么这是否有效?或者为什么这不起作用?

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 的值将与 2count > 的值进行比较.3count >= 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;
}

但这不是 switch 应该被使用的方式.

But that’s not how switch is supposed to be used.

使用 if 语句代替:

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

<小时>

编辑 由于您只使用 switch 案例(如果案例匹配则中断),我的 switch-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 >对于大于或等于 4 的 count 值,3 为真(同样).

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

要解决这个问题(写bye"和lol"表示大于或等于 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");
}

相关文章