在'if - else'语句中检查'else'中的相等性

Fre*_*man 2 javascript

假设我们有这样的代码(js):

/**
 * @param  {String} type Could be only 'high' or 'low'
 * @return {String}
 */
function getSome(type) {
    if (type == 'high') {
        return 'This is high';
    } else if (type == 'low') {
        return 'This is low';
    }
}
Run Code Online (Sandbox Code Playgroud)

如果这个变体比这更好(我不包括注释;它们是相同的)?:

function getSome(type) {
    if (type == 'high') {
        return 'This is high';
    } else {
        return 'This is low';
    }
}
Run Code Online (Sandbox Code Playgroud)

我多次遇到类似的情况.通常我没有考虑最好的变体,并写了第一个.但现在我想决定将来使用哪种变体.

最后一个问题.如果我需要检查变量的相等性,else如果变量只有两个值,并且第一个值是在if语句中给出的?我也想知道使用函数注释如何影响答案.

Tim*_*imo 9

如果只有值highlow有效,请考虑第三个选项:

function getSome(type) {
    if (type === 'high') {
        return 'This is high';
    } else if (type === 'low') {
        return 'This is low';
    } else {
        throw new Error(type + ' is invalid');
    }
}
Run Code Online (Sandbox Code Playgroud)

失败快.这可以帮助您更快地发现错误.