为什么OR运算符不能在Switch语句中工作

时间:2020-04-30 08:05:50

标签: javascript switch-statement

Java Switch Statement - Is "or"/"and" possible?

在上面的示例中,有很多类似的答案为使用这种错误语法提供了很好的选择,但我还没有阅读为什么它不起作用的说明:

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

以'b'或'c'作为参数调用将返回默认值。而“ a”将(按预期)返回“前3个”。我原以为如果'b'是真实的,那么第一种情况将评估为true并返回'前3个',但事实并非如此。有人可以解释为什么吗?

2 个答案:

答案 0 :(得分:0)

它不起作用,因为第一个truthy值是通过使用logical OR ||进行严格比较而得出的。

或者,您可以使用“穿穿法”,将三个案例排成一行,例如

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';
        }
    }

答案 1 :(得分:0)

这里

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

将首先计算表达式'a' || 'b' || 'c'的值(它是'a'),然后switch将检查val是否适合case

您需要通过以下方式进行选择:

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