简体   繁体   English

Javascript switch case一直跳到default case

[英]Javascript switch case keeps skipping to the default case

My Switch case keeps on going to default.我的 Switch 机箱一直处于默认状态。

The condition is from the intersectionWord which outputs a specific keyword from an array which matches up to a word in the trigger word array aka an intersectionWord.条件来自 intersectionWord,它从一个数组中输出一个特定的关键字,该关键字匹配触发词数组中的一个词,也就是一个 intersectionWord。

const TriggerWord = ["weather", "add", "multiply", "divide", "subtract", "hi", "hello",];
const intersectionWord = TriggerWord.filter(element => request.requestContent.includes(element));

And the objective was to pass that trigger word into the switch statement to evaluate if any of those cases match up.目标是将该触发词传递到 switch 语句中,以评估这些情况是否匹配。 If they do match up it should output an alert.如果它们确实匹配,则应该 output 发出警报。 But currently it just seems to go straight to the default case every time.但目前它似乎每次都是 go 直接进入默认情况。

I don't know where it is going wrong.我不知道哪里出了问题。

 switch (intersectionWord) {
        case TriggerWord[0].toString:
            alert("Checking the weather");
            break;
        case TriggerWord[1].toString:
            alert("Doing the math");
            break;
        case TriggerWord[2].toString:
            alert("Doing multiplication");
            break;
        case TriggerWord[3].toString:
            alert("Doing the division");
            break;
        case TriggerWord[4].toString:
            alert("Doing the subtraction");
            break;
        case TriggerWord[5].toString:
            alert("Just saying Hello");
            break;
        case TriggerWord[6].toString:
            alert("Just saying Hello");
            break;

        default:
            alert("I couldn't find a TriggerWord");
    }

As noted in the comments, there are two problems with your code:如评论中所述,您的代码存在两个问题:

  • You're missing the () after .toString so it will call the function;您在.toString之后缺少() ,因此它将调用 function; also, it's not necessary to use .toString() , since they're already strings.另外,没有必要使用.toString() ,因为它们已经是字符串了。
  • intersectionWord is an array, so it will never be equal to any of the strings in TriggerWords . intersectionWord是一个数组,因此它永远不会等于TriggerWords中的任何字符串。

Instead of the switch/case statement, consider using an object:考虑使用 object 而不是switch/case语句:

const messages = {
    weather: "Checking the weather",
    add: "Doing the math",
    multiply: "Doing multiplication",
    ...
}

Then you can loop over intersectionWords , looking up the corresponding message:然后你可以遍历intersectionWords ,查找相应的消息:

intersectionWords.forEach(word => alert(messages[word]))

Or you could combine them all into a single message:或者您可以将它们全部组合成一条消息:

let actions = intersectionWords.map(word => messages[word]).join(", ");
if (actions) {
    alert(actions);
} else {
    alert("No matching activity");
}

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

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