我正在学习Javascript。我正在尝试用Js制作Rock,Paper,Scissor游戏。
let playerScore = 0;
let computerScore = 0;
let playerSelection = prompt("Choose Rock, Paper, Scissor");
let choice = ["Rock", "Paper", "Scissor"];
function computerPlay(choice) {
let computerChoice = choice[Math.floor(Math.random() * choice.length)];
return computerChoice;
}
let computerSelection = computerPlay(choice);
function playRound(playerSelection, computerSelection) {
playerSelection.toLowerCase();
if (playerSelection === computerSelection) {
console.log (`It is a tie. Player ${playerScore} vs Computer ${computerScore}`);
}
else if (playerSelection === "rock" && computerSelection === "paper") {
computerScore++;
console.log (`Computer won! Player ${playerScore} vs Computer ${computerScore}`);
}
else if (playerSelection === "paper" && computerSelection === "scissor") {
computerScore++;
console.log (`Computer won! Player ${playerScore} vs Computer ${computerScore}`);
}
else if (playerSelection === "scissor" && computerSelection === "rock") {
computerScore++;
console.log (`Computer won! Player ${playerScore} vs Computer ${computerScore}`);
}
else {
playerScore++;
console.log (`You won! Player ${playerScore} vs Computer ${computerScore}`);
}
}
playRound(playerSelection, computerSelection);
但是我的代码无法正常运行。无论我输入什么选择(Rock,Paper,剪刀),每次都会给我相同的结果,即只有其他条件语句起作用。
答案 0 :(得分:2)
在执行playerSelection.toLowerCase();之后;将其存储到相同的变量中。
toLowerCase不会更新字符串中的任何内联函数,它只是返回值,因此您将把返回值存储在某个地方
playerSelection = playerSelection.toLowerCase();
还将选择数组更改为小写
let choice = ["rock", "paper", "scissor"];