You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript多变量条件Switch语句失效问题求助

问题原因及修复方案

你这段代码的问题在于switch语句的匹配逻辑完全用错了:switch是将括号内的表达式(这里是事件对象e)和每个case后的值做严格全等(===)比较,但你的case后面是布尔值(true或false),事件对象和布尔值不可能全等,所以永远会走到default分支。

修复方式一:调整switch的匹配基准

把switch的表达式改成true,这样每个case里的布尔表达式结果会直接和true做匹配:

switch(true){
    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.`);
}

修复方式二:改用if-else(更直观)

这种分支判断场景用if-else逻辑更清晰,没必要硬套switch:

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.`);
}

额外优化:使用标准的e.key替代废弃的keyCode

keyCode已经被Web标准废弃,推荐使用兼容性更好的e.key来判断按键:

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

内容的提问来源于stack exchange,提问作者giaggi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 06:35:18