检查开关是否有箱子

时间:2012-11-19 02:15:37

标签: javascript switch-statement


在我正在研究的项目中已经出现过几次,如何在不实际执行的情况下“测试”一个开关以确定它是否有案例?

如果必须运行案例,是否有一种有效的检查方法?

提前谢谢。

if (runSwitch(switch.hasCase("casename2"))) {
    alert("I've got it!");
}
else {
    alert("nope");
}

function runSwitch(case) {
    switch (case) { // Any way to skip the function?
        case "casename0" : alert("case"); break;
        case "casename1" : alert("case"); break;
        case "casename2" : alert("case"); break;
        case "casename3" : alert("case"); break;
    }
}

3 个答案:

答案 0 :(得分:5)

无论你要检查每个案例,无论如何,通过交换机运行它是最佳选择。如果您只想在运行之前检查案例是否存在,请将它们添加到数组并检查索引是否存在。

var cases = ['case1', 'case2'];
if (cases.IndexOf('case1') >= 0) {
    // the case is there
}

答案 1 :(得分:0)

我知道确定交换机是否具有您的情况的唯一方法是实际运行case语句。如果你想知道case块是否实际运行,你可以返回一个布尔值。

function runSwitch(_case) {
    var hasCase = false;
    switch(_case) {
        case 'casename0': hasCase = true; alert('case'); break;
        case 'casename1': hasCase = true; alert('case'); break;
        case 'casename2': hasCase = true; alert('case'); break;
        case 'casename3': hasCase = true; alert('case'); break;
        default: break;
    }
    return hasCase;
}

然后,您可以使用以下命令运行该语句:

if(runSwitch('casename4')) {
    //The case statement ran
}
else {
    //The case statement did not run
}

答案 2 :(得分:0)

由于David Schwartz没有发表回答,我将发布我的解决方案(这不是一个解决方案),并根据我的理解演示并解释他的解决方案。

我的解决方案:

我只是停止使用开关并切换到JSON(数组),因为我的切换的唯一目的是根据输入设置变量。

使用数组时,检查是否存在“case”很容易(只需运行arrayVar["casename"],如果它不存在则返回undefined)并且您不需要使用数据阻塞额外的变量,运行代码稍微困难一些,因为它需要以字符串形式提供eval,但总的来说这对我来说效果更好。

没有必要发布演示或代码,因为它确实不是解决此问题的方法。

David Schwartz的解决方案:

演示:http://jsfiddle.net/SO_AMK/s9MhD/

代码:

function hasCase(caseName) { return switchName(caseName, true); } // A function to check for a case, this passes the case name to switchName, sets "just checking" to true and passes the response along
function runSwitch(caseName) { switchName(caseName); } // This is actually a mostly useless function but it helps clarify things

function switchName(caseName, c) { // And the actual function, c is the "just checking" variable, I shortened it's name to save code
    switch(caseName) { // The switch
        case "casename0" : if (c) return true; alert("case"); break; // If c is true return true otherwise continue with the case, returning from inside a case is the same as calling break;
        case "casename1" : if (c) return true; alert("case"); break;
        case "casename2" : if (c) return true; alert("case"); break;
        case "casename3" : if (c) return true; alert("case"); break;
        default: if (c) return false; break; // If nothing else ran then the case doesn't exist, return false
    }
    return c; // Even I (:D) don't understand where this gets changed, but it works
}

说明:根据需要对上面的代码进行了注释。     

相关问题