【问题标题】:javascript switch with multiple variables in case [duplicate]带有多个变量的javascript开关,以防万一[重复]
【发布时间】:2023-01-16 23:26:14
【问题描述】:

这感觉像是一个愚蠢的问题,但我无法让它发挥作用:

我正在构建一个事件处理程序,如果用户按下“enter”或“shift Enter”,我想触发两种不同的结果

我有这个代码


         switch(e){
            case (e.keyCode == 13 && !e.shiftKey):
                console.log("Enter")
                break;
            case (e.keyCode == 13 && e.shiftKey):
                console.log("Enter&Shift")
                break;
            default:
                console.log(`Sorry, we are out of it.`);
        }

但是有些东西不起作用,因为它总是默认...尽管 e.keyValue 实际上是 13 并且 e.shiftKey 是 true...所以我正确地传递了事件。

这是错误构建的开关。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您不应为此使用 switch 语句,而应使用常规的 ifelse 语句。

    if (e.keyCode == 13 && !e.shiftKey) {
        console.log("Enter");
    } else if (e.keyCode == 13 && e.shiftKey) {
        console.log("Enter&Shift");
    } else {
        console.log(`Sorry, we are out of it.`);
    }
    

    【讨论】:

    • 这是一个相当常见的重复问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 2018-07-27
    • 2013-04-26
    • 1970-01-01
    • 2020-09-23
    • 2016-07-19
    相关资源
    最近更新 更多