Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use !-1 in javascript switch-case function

Tags:

javascript

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"

like image 315
Chester Copperpot Avatar asked Dec 07 '22 21:12

Chester Copperpot


2 Answers

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");
like image 103
Raynos Avatar answered Dec 28 '22 01:12

Raynos


!-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 switching 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);
like image 22
Matt Ball Avatar answered Dec 28 '22 02:12

Matt Ball