Can I check if the JavaScript switch is equal in the statement?

var t = "TEST";
switch(t){
    case !"TEST": /* <- does not work. Can you check if t does NOT contain a string? */
        alert("t != TEST");
    break;
}

Can you do this with a switch statement?

+4
source share
5 answers

You can use if. If you prefer the switch, use the "default" case and the if condition, for example

default:
    if(n == -1){
        //Your code
    }
    break;
+4
source

you can use typeof:

<script>
        var t =((typeof "Test")=='string')?true:false;
        switch(t){
            case false:
                alert("t != TEST");
                break;
        }
</script>
+3
source

case true. , ( ), , :

var t = "TEST";
switch(typeof t){
    case "string":
    break;
    default:
        alert("t is not a string");
    break;
}

:
, , ?

var t = "TEST";
switch(t){
    case t:
        if ("string" != typeof t) {
            alert("t is not a string");
            break;
        }
    case "TEST":
        alert("case 2");
        break;
    case "something_else":
        alert("case 3");
        break;
}

: http://jsfiddle.net/Rz7Sf/. t , .

+3

You can also do this:

var str = "TEST";

switch (true) {
    case (str !== "TEST") :
        alert("str !== TEST");
        break;
    case (str === null) :
        alert("str is null");
        break;
    default:
        alert("default trigger");
}
+3
source

Say:

var t = "TEST";
switch(t){
    case "TEST": 
        break;
    default:
        alert("This is the case you want");
        break;
}
+1
source

All Articles