JavaScript Switch Case始终跳转到Default分支问题求助
Switch Case 总是跳转到default分支的解决办法
问题根源
- 你用
filter获取intersectionWord,但filter返回的是数组(哪怕只匹配到一个关键词,它也是长度为1的数组),而switch的case都是字符串,类型不匹配,所以永远进default分支。 case里写的TriggerWord[0].toString是错误的:这是引用了toString方法本身,不是调用它得到字符串值。而且TriggerWord里的元素本来就是字符串,完全没必要用toString。
修复后的代码
把filter换成find(只取第一个匹配的关键词),同时修正switch的case写法:
const TriggerWord = ["weather", "add", "multiply", "divide", "subtract", "hi", "hello"]; // 用find返回第一个匹配的字符串,而非数组 const intersectionWord = TriggerWord.find(element => request.requestContent.includes(element)); switch (intersectionWord) { case TriggerWord[0]: // 直接用数组内的字符串值,也可以直接写"weather" alert("Checking the weather"); break; case TriggerWord[1]: alert("Doing the math"); break; case TriggerWord[2]: alert("Doing multiplication"); break; case TriggerWord[3]: alert("Doing the division"); break; case TriggerWord[4]: alert("Doing the subtraction"); break; case TriggerWord[5]: case TriggerWord[6]: // 两个触发词逻辑一致,可合并case alert("Just saying Hello"); break; default: alert("I couldn't find a TriggerWord"); }
额外说明
如果你的场景需要匹配多个关键词并分别执行逻辑,那可以保留filter,但要遍历返回的数组逐个处理,不能直接把数组传入switch。
内容的提问来源于stack exchange,提问作者onaikepo
相关产品推荐
相关产品推荐

