有可能检查一个开关是否碰到一个案件?

时间:2018-01-10 16:52:05

标签: javascript switch-statement

让我们假设我有一堆带有一堆案例的开关语句(假设超过10)。而不是做类似的事情:

switch(str) {
    case "foo":
        //do something
        caseHit = true;
        break;
}

if(caseHit) {
    //do something
}

是否可以简单地检查一下开关是否碰到了任何一种情况?我可以将它添加到交换机中的default,所以我可以这样做:

var caseHit = true;

switch(str) {
    case "foo":
        //do something
        caseHit = true;
        break;

    default:
        caseHit = false;
        break;
}

if(!caseHit) {
    //do something
}

但我不认为这是一种很好的方式。

编辑:

Andreas发布了一个很好的方法:一个对象。以下是更好地完成所有这些操作的示例:

const commands = {
    "play": play(),
    "pause": pause()
}

if (typeof commands[str] === "function") {
    commands[str]();
    //and so something else
}

2 个答案:

答案 0 :(得分:1)

我认为这是做到这一点的方法,但你可以采取乐观的态度:

select storeid, orderId, createdDate,
         case 
                    when generatedBy = 0 and (createdDate between '2018-01-09 23:45:00' and '2018-01-09 23:45:59')  
                    then 'Auto' 
                    when generatedBy = 0
                    then 'PDA Trigger'
                    when generatedBy > 0
                    then 'User Trigger'
                    end as 'Triggered By'
from mb_delinotestaging
where createdDate between '2018-01-09' and '2018-01-10'
;

这样,您无需在每种情况下var caseHit = true; //optimistic approach, it will hit a case switch(str) { case "foo": //do something break; default: caseHit = false; // if it hit the default it didn't go into any other case's code, unless there's been a waterfall in the switch statement (no break; in any of your cases) break; } if(!caseHit) { //do something }

答案 1 :(得分:-3)

嗯,在你的情况下你可以做到

if (str === 'someCase') //do something

我想。