OR 逻辑运算符在 if 语句中返回 truthy 时返回 falsey

OR logical operator within an if statement returning truthy when falsey

function doesItStartWithJ (name) {
    if(name.charAt(0) === "J" || "j") {
        return "Hello " + name + "!";
    } else {
        return "Who are you?";
    }
}

我试图使用上面的代码来解决问题,但在使用小写名称的测试用例上不断出错,我发现我必须修复我的 if 条件才能使代码正常工作,因此:

function doesItStartWithJ (name) {
    if(name.charAt(0) === "J" || name.charAt(0) === "j") {
        return "Hello " + name + "!";
    } else {
        return "Who are you?";
    }
}

我想我必须再次使用 charAt 方法来处理小写字母。 为什么这不起作用

name.charAt(0) === "J" || "j"

但适用于

name.charAt(0) === "J" || name.charAt(0) === "j"

???

您可以使用 toLowerCase :

function doesItStartWithJ (name) {
    //Will cover "J" and "j"
    if(name.charAt(0).toLowerCase() === "j") {
        return "Hello " + name + "!";
    } else {
        return "Who are you?";
    }
}