2017-11-04 183 views
1

第一個函數包含輸入,第二個函數包含if/else邏輯。我先調用第二個函數,但if/else語句似乎不起作用。Javascript:調用另一個函數內部的函數

var choice = function(){ 
 

 
    var userChoice = prompt("Do you choose rock, paper or scissors?"); 
 
    var computerChoice = Math.random(); 
 
    if (computerChoice < 0.34) { 
 
    \t computerChoice = "rock"; 
 
    } else if(computerChoice <= 0.67) { 
 
    \t computerChoice = "paper"; 
 
    } else { 
 
    \t computerChoice = "scissors"; 
 
    } console.log("Computer: " + computerChoice); 
 
    compare(userChoice, computerChoice); 
 
}; 
 

 
var compare = function(choice1, choice2){ 
 

 
    if(choice1 === choice2){ 
 
     return "The result is a tie!"; 
 
    } 
 
    else if(choice1 === "rock"){ 
 
     if(choice2 === "scissors"){ 
 
      return "rock wins"; 
 
     } 
 
     else{ 
 
      return "paper wins"; 
 
     }  
 
    } 
 
    else if(choice1 === "paper"){ 
 
     if(choice2 === "rock"){ 
 
      return "paper wins"; 
 
     } else{ 
 
      return "scissors wins"; 
 
     } 
 
    } 
 
    else if(choice1 === "scissors"){ 
 
     if(choice2 === "rock"){ 
 
      return "rock wins"; 
 
     } else{ 
 
      return "scissors wins"; 
 
     } 
 
    } 
 
    else{ 
 
     return "invalid input"; 
 
    } 
 
}; 
 

 
choice();

+0

你'比較()'函數返回一個你不以任何方式使用的字符串。如果你想讓用戶看到結果,請嘗試alert(compare(userChoice,computerChoice));'。 – nnnnnn

回答

0

它運作良好。

compare(userChoice, computerChoice) 

返回相應的結果。

但是,您沒有顯示它。因此,與alert()顯示它,等:

alert(compare(userChoice, computerChoice)); 
相關問題