Javascript JS开关盒不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11152768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:41:56  来源:igfitidea点击:

JS switch case not working

javascriptswitch-statement

提问by Chris

I have a switch case statement that doesn't work. I've checked the input, it's valid. If user is 1, it goes to default. If user is any number, it defaults. What's wrong here? I don't know javascript well at all.

我有一个不起作用的 switch case 语句。我检查了输入,它是有效的。如果用户是 1,它会进入默认值。如果用户是任何数字,则为默认值。这里有什么问题?我根本不了解 javascript。

switch (user) {
case 1:
    // stuff
    break;
case 2:
    // more stuff
    break;
default:
    // this gets called
    break;
}

回答by EyalAr

Make sure you are not mixing strings and integers.
Try:

确保您没有混合字符串和整数。
尝试:

switch (user) {
    case "1":
        // stuff
        break;
    case "2":
        // more stuff
        break;
    default:
        // this gets called
}

回答by mahadeb

Problem is data type mismatch. cast type of userto integer.

问题是数据类型不匹配。将用户类型强制转换为整数。

回答by abuduba

Cast type of user variable to integer

将用户变量类型转换为整数

 switch (+user) {   
    case 1: .. //
 }

回答by disjunction

Javascript is type-aware. So '1' is not the same as 1. In your case the "user" has to be numeric, not the string. You can cast it by just:

Javascript 是类型感知的。所以 '1' 与 1 不同。在您的情况下,“用户”必须是数字,而不是字符串。您可以通过以下方式进行投射:

user = Number(user)