我可以用var computerChoice = Math.random();
做到這一點......並將該變量轉換爲石頭,紙張或剪刀......但現在我無法獲得變量「優勝者」來更改,以便打印出結果。它只是打印出'未定義'。幫幫我?更改JavaScript變量的功能?
var choice1 = userChoice;
var choice2 = computerChoice;
var winner = "undefined";
var compare = function (choice1, choice2) {//start function
if (choice1 === choice2) {
winner = "Tie game!";
} else if (choice1 === "rock") {
if (choice2 === "scissors") {
winner = "rock wins";
} else {
winner = "paper wins";
}
} else if (choice1 === "paper") {
if (choice2 === "rock") {
winner = "paper wins";
} else {
winner = "scissors wins";
}
} else {
if (choice2 === "paper") {
winner = "scissors wins";
} else {
winner = "rock wins";
}
}
}//end function
confirm("You chose: " + userChoice + "\nSystem: " + computerChoice + "\nOutcome: " + winner);
compare(userChoice,computerChoice);
</script>
您必須在調用'confirm'之前調用'compare'更好。 –
請使用開關,而不是ifs它會使您的代碼更容易閱讀 – Dalorzo