使用函数更改Javascript变量?

时间:2016-05-09 20:49:43

标签: javascript

我能够使用var computerChoice = Math.random(); ...并将该变量转换为摇滚,纸张或剪刀......但现在我无法获得变量'胜利者'改变,以便打印出结果。它只是不断打印出来' undefined'。救命?

 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>

3 个答案:

答案 0 :(得分:2)

那是因为在显示之前你没有改变它。在致电compare之前致电confirm ,因为compare是更改winner的功能。

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

答案 1 :(得分:0)

您应该更改函数调用的顺序。

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

答案 2 :(得分:0)

您可以确认&#39;里面的比较&#39;功能块并删除所有这些全局变量

  

choice1,userChoice; choice2,computerChoice;

<base href="/" />

请记住,将变量locals保持在比globals更好的范围