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

Javascript switch case that runs code when any case is true? - Stack Overflow

programmeradmin1浏览0评论

I have a standard switch case block:

switch(variable) {
    case "option1":
        alert("Option 1");
        break;
    case "option2":
        alert("Option 2");
        break;
}

And I would like to run this code:

alert("Any Option");

Is there a simple way to run this code when either of the cases match, without adding the code to every case, and without rechecking "variable" (i.e. not using an if statement after the switch)?

I have a standard switch case block:

switch(variable) {
    case "option1":
        alert("Option 1");
        break;
    case "option2":
        alert("Option 2");
        break;
}

And I would like to run this code:

alert("Any Option");

Is there a simple way to run this code when either of the cases match, without adding the code to every case, and without rechecking "variable" (i.e. not using an if statement after the switch)?

Share Improve this question edited Jun 23, 2017 at 19:59 Mackija asked Jun 23, 2017 at 19:33 MackijaMackija 3172 silver badges14 bronze badges 11
  • 1 That would run both the Option 1 and Option 2 alerts, I'm looking here to run another piece of code such as alert("Both options") – Mackija Commented Jun 23, 2017 at 19:35
  • 1 @TinyGiant I don't think so. If you remove the first, then the case for option2 will erroneously execute when option1 is matched. If the second, then the code won't run if option1 was matched. If both, then the case for option2 will erroneously execute when option1 is matched. – Karl Reid Commented Jun 23, 2017 at 19:35
  • 1 @TinyGiant No... That simply creates fall-through. It will alert Option 1, Option 2, etc. – mhodges Commented Jun 23, 2017 at 19:36
  • 1 I misunderstood. No, you cannot do that. You would have to run another separate check. You can do the opposite (if no matches then default) – user4639281 Commented Jun 23, 2017 at 19:37
  • 1 If you want to run the same code when either case matches, put the code in both case blocks. – Dave Rager Commented Jun 23, 2017 at 19:48
 |  Show 6 more ments

5 Answers 5

Reset to default 3

There are a bunch of really hacky ways to do what you are suggesting (named do loops with break/continue, recursive functions with switch statements, etc.) but the cleanest would be to use a function, like so:

var variable = "option1";

function checkValue (val) {
    switch (variable) {
        case "option1":
            alert("Option 1");
            return true;
        case "option2":
            alert("Option 2");
            return true;
        default: 
            return false;
    }
}

if (checkValue(variable)) {
    // run mon code
    alert("Any option");
}

Why not making a function called by both cases?

switch(variable) {
case "option1":
    dualAlert("Option 1");
    break;
case "option2":
    dualAlert("Option 2");
    break;
}

function dualAlert(text){
    alert(text);
    alert('Common Alert');
}

A labeled block allows you to break out of it at any time. If you break in the default case, you can run some code following the switch statement when either of the cases match and without rechecking the variable, as requested:

let variable = prompt("option1 or option2?");

select: {
  switch(variable) {
    case "option1":
        alert("Option 1");
        break;
    case "option2":
        alert("Option 2");
        break;
    default:
        break select;
  }
  alert("Both Options");
}

However, I don't remend this! Labels make the code execution path less clear. Above code is not readable. Rechecking the variable is a better approach.

Not directly with a switch statement. See The Switch Statement, ECMAScript 2016 standard.

In particular:

  • Runtime Semantics: Switch Evaluation
  • Runtime Semantics: CaseBlockExpression

The language spec does not contain the feature that you are looking for.

I don't think i would ever use the pattern you described, nonetheless something like this could suit your needs.

/**
 * Use this method to simulate a "finally" statement in a
 * method that resembles a switch
 *
 * @param {*} value - The value to pare
 * @param {Array<*, boolean, function>} options - The collection of switch statements
 *   First value is the value to pare against the original value
 *   Second value specifies if this statement should behave like a break at its end
 *   Third value is the action to take when the value matches
 * @param {function} finallyFn - The method which is run if any statement was executed
 */
function switchWithFinally(value, options, finallyFn) {
    var matched = false,
        breakSwitch = true;
    for(var i = 0; i < options.length; i++) {
        if(!breakSwitch || value === options[i][0]) {
            options[i][2]();
            matched = true;
            breakSwitch = options[i][1];
        }
    }
    if(matched) finallyFn();
}

/**
 * Example call, should return
 *   Option 2
 *   Option 3
 *   Any option
 */
switchWithFinally(
    'option2',
    [
        ['option1', true, function() {
            console.log('Option 1');
        }],
        ['option2', false, function() {
            console.log('Option 2');
        }],
        ['option3', true, function() {
            console.log('Option 3');
        }]
    ],
    function() {
        console.log('Any option');
    }
);
发布评论

评论列表(0)

  1. 暂无评论