开发者

Boolean operators in a switch statement?

Is there any way to make this work with a switch, syntactically?

switch(i){
    case ('foo' || 'bar'):
        alert('foo or bar');
        break;
    default:
        alert('not 开发者_如何学编程foo or bar');
}


switch(i){
  case 'foo':
  case 'bar':
    alert('foo or bar');
    break;
  case 'other':
  default:
    alert('other');
}

Note: "other" isn't required, I'm just showing that you can stack cases with default as well.


From the official Mozilla Developer Center docs, use multiple cases like so:

 // multiple cases:      

   case "Mangoes":  
   case "Papayas":  
      document.write("Mangoes and papayas are $2.79 a pound.<br>");  
      break;  
   default:  
      document.write("Sorry, we are out of " + expr + ".<br>");  
 }

Or if looking for an IE solution you would use the JScript docs for switch which refer to case conditions as "labels" and states:

multiple label blocks are executed if a break statement is not used.

Effectively both sets of documentation say the same thing about putting multiple cases together.


JavaScript doesn't work that way. Do it like this:

switch(i){
    case 'foo':
    case 'bar':
        alert('foo or bar');
        break;
    default:
        alert('not foo or bar');
}

Like in C, JavaScript's case clause will cascade.


switch(i){
    case 'foo':
    case 'bar':
        alert('foo or bar');
        break;
    default:
        alert('not foo or bar');
}


Would something along this line work?

switch(i){ 
    case ('foo'):
    case ('bar'): 
        alert('foo or bar'); 
        break; 
    default: 
        alert('not foo or bar'); 
} 


switch(i)
{
    case 'foo':
    case 'bar':
        alert('foo or bar');
        break;
    default:
        alert('not foo or bar');
        break;
}


You have to set separate cases for each value.

switch(i)
{ 
    case 'foo': 
    case 'bar': 
        alert('foo or bar'); 
        break; 
    default: 
        alert('not foo or bar'); 
}

Using your code, you'll only get the alert if i evaluates to true, since a string that is not empty also evaluates to true.


The problem with your example is that the expression ('foo' || 'bar') evaluates to 'foo', and therefore it will only match when i is 'foo', and never when i is 'bar'.

The || operator produces the value of its first operand if the first operand is truthy. Otherwise it produces the value of the second operand. A non-empty string is always truthy, and that's why your expression is returning 'foo'.

However, in JavaScript each case falls through into the next case unless you explicitly disrupt the flow with a break or a return. Therefore you can easily make it work as follows:

switch(i) {
    case 'foo':
    case 'bar':
        alert('foo or bar');
        break;
    default:
        alert('not foo or bar');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜