简体   繁体   English

JS开关盒无法正常工作

[英]JS switch case not working

I have a switch case statement that doesn't work. 我有一个不起作用的switch case语句。 I've checked the input, it's valid. 我检查了输入,它是有效的。 If user is 1, it goes to default. 如果user为1,则为默认值。 If user is any number, it defaults. 如果用户是任何号码,则默认为。 What's wrong here? 这有什么不对? I don't know javascript well at all. 我根本不懂javascript。

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

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
}

Problem is data type mismatch. 问题是数据类型不匹配。 cast type of user to integer. 用户类型转换为整数。

Cast type of user variable to integer 将用户变量的类型转换为整数

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

Javascript is type-aware. Javascript是类型感知的。 So '1' is not the same as 1. In your case the "user" has to be numeric, not the string. 因此'1'与1不同。在您的情况下,“user”必须是数字,而不是字符串。 You can cast it by just: 您可以通过以下方式投射它:

user = Number(user)

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

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