简体   繁体   English

有条件地返回或打破开关盒

[英]Conditionally return or break a switch case

I am refactoring a switch statement in which I am performing am if conditional within one of the cases where the if will break the switch case and the else will return .我正在重构一个 switch 语句,我在其中执行 am if条件,其中ifbreak switch case 而elsereturn

Is it possible to perform this as a quicker conditional such as a Ternary or something else, rather than a standard if/else?是否可以将其作为更快的条件执行,例如三元或其他条件,而不是标准的 if/else?

Original原版的

let someCondition;

// someCondition is set at some point

switch(toSwitchOn) {
    case myCase:
        if (someCondition) {
           sendObj({someKey: 'someVal', condition: true});
           break;
        } else {
           sendObj({condition: false});
           return false;           
        }
}

Refactored so far到目前为止重构

let someCondition;

// someCondition is set at some point

switch(toSwitchOn) {
    case myCase:
        sendObj({
           ...!!someCondition && {someKey: 'someVal'},
           condition: !!someCondition
        });
     
        if (someCondition) { break; } else {return false}
}

It depends on what "performing" means to you, but your code should be clear and easy to read, as other people have already answered in the comments.这取决于“执行”对您意味着什么,但是您的代码应该清晰易读,正如其他人已经在评论中回答的那样。

You can take a look at these topics: Definition of 'clean code' and To ternary or not to ternary?您可以查看以下主题: “干净代码”的定义要三元还是不要三元?

you can do something like this你可以这样做

let someCondition;

// someCondition is set at some point

switch(true) {
    case someCondition:
         sendObj({someKey: 'someVal', condition: true});
         break;
    default:
         sendObj({condition: false});
         return false;           
    }

try this:尝试这个:

let someCondition

// someCondition is set at some point

switch (toSwitchOn) {
    case myCase: {
        const result = handleCondition()
        if (result) break
        else return false
    }
}
function handleCondition() {
    let obj, result
    if (someCondition) {
        obj = { someKey: "someVal", condition: true } 
        result = true
    } else {
        obj = { condition: false }
        result = false
    }
    sendObj(obj)
    return result
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM