最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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"

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"

Share Improve this question edited Jun 4, 2011 at 17:48 no.good.at.coding 20.4k2 gold badges62 silver badges51 bronze badges asked Jun 4, 2011 at 17:47 Chester CopperpotChester Copperpot 1461 silver badge7 bronze badges 1
  • 1 If you want to use indexOf in a 'switch'; the best you can do is chain a bunch of if and else if(s) – Kevin Commented Jun 4, 2011 at 17:54
Add a ment  | 

7 Answers 7

Reset to default 8

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 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);

Your bination of "not"(!) and "-1" seems faulty. You need to move them to your cases like this

var mystring='my name is johnny';  
switch (true) {  
          case mystring.indexOf('hello') != -1:  
        alert('hello');  
        break;  
    case mystring.indexOf('goodbye') != -1:  
        alert('goodbye');  
        break;  
    case mystring.indexOf('johnny') != -1:  
        alert('johnny');  
        break;  
    default:  
        alert('default');           
}

It's a pain in PHP that strpos(...) returns false when not found and 0 when string starts with it (and those 2 values are ==, but not ===) but I personally find JavaScripts indexOf(..) == -1 even worse. (Why can't it be false or null?)

What's happening here is you're switching the result of !-1 and that case isn't found. switch-case doesn't seem to be the right construct to use here.

The expression !-1 will just evaluate to false.

You are trying to convert a parison like x != -1 into x == !-1, but the ! operator doesn't negate the parison, only the value.

I don't think your implementation is correct. The proper conditional statement to use is if... else.

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');
else alert('default');

The switch should be mystring, example:

http://www.w3schools./js/js_switch.asp

发布评论

评论列表(0)

  1. 暂无评论