Reputation: 7310
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 (user) {
case 1:
// stuff
break;
case 2:
// more stuff
break;
default:
// this gets called
break;
}
Upvotes: 19
Views: 41370
Reputation: 3170
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
}
Upvotes: 38
Reputation: 656
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:
user = Number(user)
Upvotes: 6
Reputation: 5042
Cast type of user variable to integer
switch (+user) {
case 1: .. //
}
Upvotes: 13