I "want" to use switch, but i can't seem to get it to work when I use it in this fashion. Anyone know why?
var mystring='my name is johnny';
switch (!-1) {
case mystring.indexOf('hello'):
alert('hello');
break;
case mystring.indexOf('goodbye'):
alert('goodbye');
break;
case mystring.indexOf('johnny'):
alert('johnny');
break;
default:
alert('default');
}
it always alerts "default", but you can see that I want it to alert "johnny"
Disclaimer: This switch is evil. Use if/else-if statements. but if you must use a switch it can be done as such:
switch (true) {
case /hello/.test(mystring):
alert('hello');
break;
case /goodbye/.test(mystring):
alert('goodbye');
break;
case /johnny/.test(mystring):
alert('johnny');
break;
default:
alert('default');
}
Should work as you want it to.
.test
.
I would be tempted to refactor it further.
function Parse(str) {
var logic = {
"hello": function(str) { alert("hello"); }
/*, ... */
}
for (var k in logic) {
if ((new RegExp(k)).test(str)) {
logic[k](str);
}
}
}
Parse("Hello I am johnny");
!-1
coerces -1
to a boolean, and then negates it, so
switch(!-1)
{
// stuff
}
is equivalent to
switch(false)
{
// stuff
}
Since there is no case false
, the default
will always be executed. This is really not the right way to use a switch — there is no point in switch
ing on a constant expression.
Why do you "want" to use a switch
?
Here's how to implement it correctly:
var mystring='my name is johnny';
if (mystring.indexOf('hello') !== -1) alert('hello');
else if (mystring.indexOf('goodbye') !== -1) alert('goodbye');
else if (mystring.indexOf('johnny') !== -1) alert('johnny');
Or, less repetetively,
var mystring='my name is johnny',
words = ['hello', 'goodbye', 'johnny'],
word;
while (word = words.shift(), mystring.indexOf(word) === -1);
word = word || 'default';
alert(word);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With