2016-05-09 111 views
0

我可以用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> 
+1

您必須在調用'confirm'之前調用'compare'更好。 –

+0

請使用開關,而不是ifs它會使您的代碼更容易閱讀 – Dalorzo

回答

2

這是因爲在顯示它之前沒有改變它。致電compare之前您致電confirm,因爲compare是更改winner的功能。

compare(userChoice, computerChoice); 
confirm("You chose: " + userChoice + "\nSystem: " + computerChoice + "\nOutcome: " + winner); 
0

您應該改變函數調用的順序。

compare(userChoice,computerChoice); 
confirm("You chose: " + userChoice + "\nSystem: " + computerChoice + "\nOutcome: " + winner); 
0

你可以把「確認」的「比較」功能塊內,並刪除所有這些全局變量

選擇1,userChoice的; choice2,computerChoice;

 var compare = function (choice1, choice2) {//start function 

     var winner; //you don't need to specify 'undefined' 

     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"; 
      } 
     } 

confirm("You chose: " + choice1+ "\nSystem: " + choice2+ "\nOutcome: " + winner); 

    }//end function 

請記住您的變量當地人的範圍比全局