我试图弄清楚如何比较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);
答案 0 :(得分:3)
// ...
else if (choice1 !== "rock" || choice1 !== "paper" || choice1 !== "scissors") {
return "Your only options are rock, paper, or scissors you friggin plebian!";
}
// ...
布尔表达式不像我们用英语说的那样读,即“选择不是摇滚,纸或剪刀”。将“choice”评估为布尔值是在某些语言中完美的语法有效的事情,所以要记住要记住愚蠢地重复参数。否则这些是需要一段时间才能找到的错误类型。 ;)
答案 1 :(得分:2)
尝试:
else if (choice1 !== "rock" || choice1 !== "paper" || choice1 !== "scissors")
你的陈述并没有编译为&#34; choice1不等于摇滚,纸张或剪刀。&#34;
编译器将其读作:
choice1不等于摇滚
OR
纸
OR
剪
逻辑运算符之后的每个部分都必须求值为布尔值,所以只有匹配字符串才能匹配,如果它不是摇滚,则后两个不匹配。
答案 2 :(得分:1)
else if (choice1 !== "rock" || "paper" || "scissors")
应该是:
else if (choice1 !== "rock" || choice1 !== "paper" || choice1 !== "scissors")