这是代码。建造“岩石,纸,剪刀”
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") {
if (choice2 === "scissors") {
return "rock wins"
}
else {
return "paper wins"
}
} compare(userChoice,computerChoice); //I forget to add it. Now I add it.
我不明白为什么我需要添加else { return "paper wins" }
答案 0 :(得分:0)
===
运算符是javascript中的strict equality运算符。有问题的if
语句正在对choice1
和字符串文字"rock"
进行比较。如果该答案为真,则执行下一个if
语句,程序将检查choice2
是否等于"scissors"
。如果这个陈述是真的而不是它返回"rock wins"
,因为每个人都知道摇滚节拍剪刀。
答案 1 :(得分:0)
如果choice1
为"rock"
且choice2
不是else
)"scissors"
,那么choice2
可能是"paper"
或"rock"
。由于没有平局,choice2
不能为"rock"
,因此choice2
为"paper"
,"paper"
为"rock"
,所以{{1} }。
修改强>
由于"paper wins"
语句在
return
这意味着您可以避开 if (choice2 === "scissors") {
return "rock wins" // <-- quit the function
}
// <-- if you got here it is not true that (choice2 === "scissors")
return "paper wins"
而只是else
答案 2 :(得分:0)
我不明白为什么我需要添加其他{return“paper wins”}
因为这个游戏有3种不同的情况(比方说我选择摇滚):