在 IF 语句中比较字符串与逻辑运算符

Comparing strings with logical operators in an IF statement

我想知道如何比较 if 语句中的字符串。我的大部分代码都可以忽略,但有上下文。我正在尝试向我的简单石头剪刀布游戏添加一条消息,以便在有人输入除了石头剪刀布之外的字符串时显示。有人能告诉我我在周围有星号的部分做错了什么吗?

var userChoice = prompt("Do you choose rock, paper or scissors?");

var computerChoice = Math.random();

if (computerChoice < 0.34) {
     computerChoice = "rock";
} else if(computerChoice <= 0.67) {
     computerChoice = "paper";
} else {
    computerChoice = "scissors";
} console.log("Computer: " + computerChoice);

var compare = function (choice1, choice2) {
    if (choice1 === choice2) {
        return "The result is a tie!";
     }
**else if (choice1 !== "rock" || "paper" || "scissors") {
    return "Your only options are rock, paper, or scissors you friggin plebian!";
}**
else if (choice1 === "rock") {
    if (choice2 === "scissors") {
        return "Rock wins!";
    }
    else {
        return "Paper wins!";
    }
}
else if (choice1 === "paper") {
    if (choice2 === "rock") {
        return "Paper wins!";
    }
    else {
        return "Scissors wins!";
    }
}
else if (choice1 === "scissors") {
    if (choice2 === "paper") {
        return "Scissors wins!";
    }
    else {
        return "Rock wins!";
    }
}

};

compare (userChoice, computerChoice);

else if (choice1 !== "rock" || "paper" || "scissors") 应该是:

else if (choice1 !== "rock" || choice1 !== "paper" || choice1 !== "scissors")

// ...
else if (choice1 !== "rock" || choice1 !== "paper" || choice1 !== "scissors") {
    return "Your only options are rock, paper, or scissors you friggin plebian!";
}    
// ...

布尔表达式读起来不像我们用英语说的那样,即 "Choice is not rock or paper or scissors"。在某些语言中,将 "choice" 计算为布尔值在语法上是完全有效的,因此请注意记住要愚蠢地重复该参数。否则,这些都是需要一段时间才能发现的错误类型。 ;)

尝试:

else if (choice1 !== "rock" || choice1 !== "paper" || choice1 !== "scissors")

您的语句未编译为 "choice1 not equal to rock, paper, or scissors."

编译器读作:

choice1 不等于 rock

论文

剪刀

逻辑运算符之后的每个部分都必须计算为布尔值,因此它只匹配不是 rock 的字符串,后两个不匹配任何内容。