简体   繁体   English

为什么 OR 运算符在 Switch 语句中不起作用

[英]Why don't OR operators work in Switch statements

Java Switch Statement - Is "or"/"and" possible? Java Switch 语句 - “或”/“与”可能吗?

There are quite a few answers like the above that give good alternatives to using this erroneous syntax in my example but I haven't read an explanation to why it doesn't work:在我的示例中,有很多类似上面的答案可以很好地替代使用这种错误语法,但我还没有阅读到为什么它不起作用的解释:

const switchExample = (val) => {
    switch(val) {
        case 'a' || 'b' || 'c':
        return 'first 3'
        break;
        case 'd':
        return 'fourth'
        break;
        default:
        return 'default'
    }
}

Invoking with 'b' or 'c' as a param will return the default.使用 'b' 或 'c' 作为参数调用将返回默认值。 Whereas 'a' will return (as expected) 'first 3'.而“a”将返回(如预期的那样)“前 3”。 I was expecting that if 'b' was truthy, then the first case would evaluate to true and return 'first 3' but this ins't the case.我期待如果“b”是真的,那么第一个案例将评估为真并返回“前 3”,但事实并非如此。 Can somebody explain why?有人可以解释为什么吗?

It does not work, because the first truthy value is taken by using logical OR ||它不起作用,因为第一个值是通过使用逻辑 OR ||获取的for a strict comparison.进行严格比较。

Alternatively, you could use a fall through approach with having three cases in a line, like或者,您可以使用贯穿式方法,将三个案例排成一行,例如

const
    switchExample = (val) => {
        switch(val) {
            case 'a':
            case 'b':
            case 'c':
                return 'first 3'; // no break required, because return ends the function
            case 'd':
                return 'fourth';
            default:
                return 'default';
        }
    }

Here这里

    switch(val) {
        case 'a' || 'b' || 'c':

the value of the expression 'a' || 'b' || 'c'表达式'a' || 'b' || 'c' 'a' || 'b' || 'c' 'a' || 'b' || 'c' will be first evaluated (it's 'a' ), and then the switch will examine whether val fits the case . 'a' || 'b' || 'c'将首先被评估(它是'a' ),然后switch将检查val是否适合case

You need to do the alternative this way:您需要以这种方式进行替代:

    switch(val) {
        case 'a':
        case 'b':
        case 'c':
            return 'first 3';
        case 'd':
// ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM