Reputation: 4787
Is there a way in Javascript to use the non-strict comparison in a switch statement ?
Example:
if (item == '3') { ... }
else if (item == 'Chocolate') { ... }
else { ... }
In a switch:
switch (item){
case '3':
... break;
case 'Chocolate':
... break;
default:
...
}
I would like to test if item equals 3 (number) or '3' (char) in one case. I would like to avoid to write two cases for the same instructions.
Is it possible ?
Upvotes: 0
Views: 168
Reputation: 1191
switch(item.toString()){
case "3" :
[...]
will behave as you want. it is a little hacky but it works.
As seen in comments below, there are many caveats to this however. It will work exactly as intended if you are sure that item is always a string or number.
booleans will be, well "true"
or "false"
, and as such not fall into "0" and "1" cases.
objects, unless you have changed their toString method, will fall in a "[object Object]"
case.
Arrays of one element will "toString" into the same case as their only elements.
I'll reiterate that you're probably way safer with using fall-through.
I've tried to override Object.prototype.valueOf as can be seen in fake-operator-overloading. the switch statement, however, doesn't call valueOf, so that's off the table. Now if you REALLY want the switch
semantics AND an ==
, you can do this :
switch(true){
case key == 1 :
//...
break;
case key == "something" :
//...
break;
case key == false :
//...
break;
default :
}
this method taken from mozilla doc
Now, to me that seems very complex for not a lot of bonus. but here you have it. I'm not even sure what case would some values such as {}
or NaN
fall into, but for example ""
and 0
would go into false
provided nothing catches them before
Upvotes: 4
Reputation: 10093
You can do it like this (It's called fall-through):
switch (item){
case '3':
case 3:
... break;
case 'Chocolate':
... break;
default:
...
}
Upvotes: 1