IT story

JavaScript에서 break 문을 사용하는 것보다 switch 문을 반환하는 것이 더 나은 방법으로 간주됩니까?

hot-time 2020. 5. 19. 08:08
반응형

JavaScript에서 break 문을 사용하는 것보다 switch 문을 반환하는 것이 더 나은 방법으로 간주됩니까?


옵션 1-리턴을 사용하여 전환 :

function myFunction(opt) 
{
    switch (opt) 
    {
        case 1: return "One";
        case 2: return "Two";
        case 3: return "Three";

        default: return "";
    }    
}

옵션 2-중단을 사용하여 전환 :

function myFunction(opt) 
{
    var retVal = "";

    switch (opt) 
    {
        case 1: 
            retVal = "One";
            break;

        case 2: 
            retVal = "Two";
            break;

        case 3: 
            retVal = "Three";
            break;
    }

    return retVal;
}

나는 두 가지가 모두 작동한다는 것을 알고 있지만 가장 좋은 방법 중 하나입니까? 나는 옵션 1을 선호하는 경향이 있습니다-더 깨끗하고 간단하기 때문에 return return을 사용하십시오.


다음은 @ ic3b3rg의 의견에 언급 된 기술을 사용하는 특정 예제의 jsFiddle입니다 .

var SFAIC = {};

SFAIC.common = 
{
    masterPages: 
    {
        cs: "CS_",
        cp: "CP_"
    },

    contentPages: 
    {
        cs: "CSContent_",
        cp: "CPContent_"    
    }
};

function getElementPrefix(page) 
{
    return (page in SFAIC.common.masterPages)
        ? SFAIC.common.masterPages[page]
        : (page in SFAIC.common.contentPages)
            ? SFAIC.common.contentPages[page]
            : undefined;
}

함수를 호출하려면 다음과 같은 방법으로 수행하십시오.

getElementPrefix(SFAIC.common.masterPages.cs);
getElementPrefix(SFAIC.common.masterPages.cp);
getElementPrefix(SFAIC.common.contentPages.cs);
getElementPrefix(SFAIC.common.contentPages.cp);

여기서 문제는 항상 정의되지 않은 값을 반환한다는 것입니다. 속성이 아닌 객체 리터럴의 실제 값을 전달하기 때문이라고 생각합니다. @ ic3b3rg의 의견에 설명 된 기술을 사용 하여이 문제를 해결하려면 어떻게해야 합니까?


A break will allow you continue processing in the function. Just returning out of the switch is fine if that's all you want to do in the function.


It depends, if your function only consists of the switch statement, then I think that its fine. However, if you want to perform any other operations within that function, its probably not a great idea. You also may have to consider your requirements right now versus in the future. If you want to change your function from option one to option two, more refactoring will be needed.

However, given that within if/else statements it is best practice to do the following:

var foo = "bar";

if(foo == "bar") {
    return 0;
}
else {
    return 100;
}

Based on this, the argument could be made that option one is better practice.

In short, there's no clear answer, so as long as your code adheres to a consistent, readable, maintainable standard - that is to say don't mix and match options one and two throughout your application, that is the best practice you should be following.

참고URL : https://stackoverflow.com/questions/6114210/in-javascript-is-returning-out-of-a-switch-statement-considered-a-better-practi

반응형