我在做一个简单的石头剪刀游戏的JavaScript项目,我似乎无法弄清楚为什么我的代码只返回“玩家获胜”,即使玩家应该输掉。这是代码:
var userChoice = prompt("Do you choose rock, paper or scissors?");
console.log("Player: " + userChoice)
var computerChoice = Math.random();
console.log(computerChoice)
if (computerChoice < 0.34) {
computerChoice = "rock"
} else if (computerChoice > 0.67) {
computerChoice = "paper"
} else {
computerChoice = "scissors"
}
console.log("Computer: " + computerChoice);
var compare = function(userChoice, computerChoice) {
var x = userChoice
var y = computerChoice
if (x === y) {
return "The result is a tie!"
}
if (x === "rock", y === "scissors") {
return "player wins"
} else if (x === "scissors", y === "paper") {
return "player wins"
} else if (x === "paper", y === "rock") {
return "player wins"
} else {
return "You lose"
}
}
compare(userChoice, computerChoice)
另外在旁注中,为什么stackoverflow上的控制台在codeacademy上的控制台没有显示返回时。
答案 0 :(得分:1)
您应该使用运算符&&
而不是,
。
var compare = function(userChoice, computerChoice) {
var x = userChoice;
var y = computerChoice;
if (x === y) {
return "The result is a tie!";
}
if (x === "rock" && y === "scissors") {
return "player wins";
} else if (x === "scissors" && y === "paper") {
return "player wins";
} else if (x === "paper" && y === "rock") {
return "player wins";
} else {
return "You lose";
}
}
答案 1 :(得分:-1)
我猜你丢了东西,也许你应该改变:
if (x === "rock", y === "scissors") {
到
if (x === "rock" && y === "scissors") {
其他条件陈述应如上所述。