首页 > 解决方案 > What is correct/clean Switch (or functions in general) control flow?

问题描述

I stumbled upon a bug with my switch statement (two cases) wherein both cases ran because the former made the latter true. I found two solutions, but I don't know which one I should use or if I should combine both.

My initial thought was simply to add breaks at the end of each case. But my coworker suggested I swap the order as the latter can't interfere with the former that way. Maybe I should do both? I think breaks are clearer at a glance, but swapping them is elegant. What would you prefer to see from your coworker?

**---OPTION 1---**
var created = false;
function clicker(){
    switch(created){
        case false:
            **some code**
            created = true;
            break;
        case true:
            **some code**
            break;
    }
}

**---OPTION 2---**
var created = false;
function clicker(){
    switch(created){
        case true:
            **some code**
        case false:
            **some code**
            created = true;
    }
}

Initially, I ran option 1 but without the breaks. Case "false" would run, make case "true" = true, then case "true" would run.

Both of these options fix it. Which is better? Do you have an even better solution?

标签: javascriptswitch-statement

解决方案


只需使用一个if语句:

function clicker() {
    if (created) {
        //Some code
    } else {
        //Some code
        created = true;
    }
}

推荐阅读