从 switch 语句中返回是否被认为是比使用 break 更好的做法?

2022-01-19 00:00:00 return break switch-statement javascript

选项 1 - 使用 return 切换:

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

        default: return "";
    }    
}

选项 2 - 使用 break 切换:

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 进行切换,因为它更干净、更简单.

I know that both work, but is one more of a best practice? I tend to like Option 1 - switch using return best, as it's cleaner and simpler.

这是我使用@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;
}

要调用该函数,我会通过以下方式进行:

To call the function, I would do so in the following ways:

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

这里的问题是它总是返回未定义的.我猜这是因为它传递的是对象文字的实际值而不是属性.我将如何使用 @ic3b3rg 的 评论中描述的技术来解决此问题?

Problem here is that it always returns undefined. I'm guessing that it's because it's passing in the actual value of the object literal and not the property. What would I do to fix this using the technique described in @ic3b3rg's comments?

推荐答案

中断将允许您继续在函数中处理.如果您只想在函数中执行此操作,只需退出开关即可.

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.

相关文章