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

Double Pipe in a Switch Case Javascript - Stack Overflow

programmeradmin2浏览0评论

I have a switch case, and I want to direct 3 different possible cases to one oute using the double pipe.

/

var type = "JPEG"

switch(type){
    case "PNG" || "JPG" || "JPEG":
    alert("works");
    break;
    default:
    alert("not working");
    break;
}

The obvious thing to do would be making a separate case for each of the file types, but there must be a more efficient way, that resembles my attempt.

I have a switch case, and I want to direct 3 different possible cases to one oute using the double pipe.

http://jsfiddle/qCA3G/

var type = "JPEG"

switch(type){
    case "PNG" || "JPG" || "JPEG":
    alert("works");
    break;
    default:
    alert("not working");
    break;
}

The obvious thing to do would be making a separate case for each of the file types, but there must be a more efficient way, that resembles my attempt.

Share Improve this question asked Sep 25, 2013 at 2:22 Philip KirkbridePhilip Kirkbride 22.9k39 gold badges131 silver badges237 bronze badges 2
  • 5 Read about "switch fallthrough". – elclanrs Commented Sep 25, 2013 at 2:23
  • Does this answer your question? Switch statement multiple cases in JavaScript – Orchis Commented Aug 18, 2020 at 15:01
Add a ment  | 

4 Answers 4

Reset to default 7

This is why switch has fall-through:

switch(type){
    case "PNG":
    case "JPG": 
    case "JPEG": 
       alert("works");
       break;
    default:
       alert("not working");
       break;
}

But fallthrough is a fickle beast! Beware the dreaded forgotten break statement

switch(type){
    case "PNG":
    case "JPG": 
    case "JPEG": 
       alert("works");
    default: // forgot break BOTH ALERTS RUN!
       alert("not working");
       break;
}

That's not the way switch case works. You need to instead create fall-through case'(skipping the break statement).

var type = "JPEG"

switch(type){
    case "PNG":  
    case "JPG":  
    case "JPEG":  
       alert("works");
    break; //break here if you dont want to fall through again
    default:
       alert("not working");
    break;
}

Yeah, there is:

        var type = "JPEG"

        switch (type) {
        case "PNG":
        case "JPG":
        case "JPEG":
            alert("works");
            break;
        default:
            alert("not working");
            break;
        }

Try

var type = "JPEG"

switch(type){
    case "PNG":
    case "JPG":
    case "JPEG":
      alert("works");
    break;
    default:
      alert("not working");
    break;
}
发布评论

评论列表(0)

  1. 暂无评论