2014-03-12 163 views
0

是否有任何理由說明此代碼無法正常工作? 我已經把整個腳本放到了一個函數中,爲了playAgain變量的緣故(見底部),將重啓爲這個函數。 任何幫助將不勝感激。Javascript:函數內的函數

function headsTails() { 
    var userChoice; 
    userChoice = prompt('Heads or Tails'); 

    function myGame(heads,tails) { 
     var result; 
     var coin; 
     result = Math.random() 
     if(result > 0.5) { 
      coin = "heads"; 
     } else { 
      coin = "tails"; 
     } 
     if(userChoice === "heads") { 
      if(coin = "heads") { 
       alert("You win!"); 
      } else if(coin = "tails") { 
       alert("You lose!"); 
      } 
     } 
     if(userChoice === "tails") { 
      if(coin = "heads") { 
       alert("You lose!"); 
      } else if(coin = "tails") { 
       alert("You win!"); 
      } 
     } 
    } 
    myGame(); 
    var playAgain; 
    playAgain = confirm(Do you want to play again?) 
    if(playAgain) { 
     headsTails(); 
    } else { 
     alert("Thanks for playing!") 
    } 
} 
+0

這是行不通的?另外,_「對不起有關雜亂的間距」 - - 真的嗎?只需修復它!這將使得有能力回答的人不太可能簡單地繼續前進而不會感到困擾。 –

+3

不應該'確認(你想再玩一次嗎?)'確認'('你想再玩一次嗎?')? – DarkAjax

+0

格式化非常重要,因爲它可以幫助您瞭解代碼可能無法正常工作的原因。重新格式化後再檢查一次,看看你能否說出爲什麼它可能沒有達到你期望的水平。 – kinakuta

回答

1

你有很多語法錯誤:

coin = "heads" -> coin === "heads" 
coin = "tails" -> coin === "tails" 
confirm(Do you want to play again ?) -> confirm("Do you want to play again ?") 

我會推薦閱讀關於JavaScript和一般在編程語言...

修正headsT​​ails功能:

function headsTails() { 
    var userChoice; 
    userChoice = prompt('Heads or Tails'); 

    function myGame(heads, tails) { 
     var result; 
     var coin; 
     result = Math.random(); 
     if (result > 0.5) { 
      coin = "heads"; 
     } else { 
      coin = "tails"; 
     } 
     if (userChoice === "heads") { 
      if (coin === "heads") { 
       alert("You win!"); 
      } else if (coin === "tails") { 
       alert("You lose!"); 
      } 
     } 
     if (userChoice === "tails") { 
      if (coin === "heads") { 
       alert("You lose!"); 
      } else if (coin === "tails") { 
       alert("You win!"); 
      } 
     } 
    } 

    myGame(); 
    var playAgain; 
    playAgain = confirm("Do you want to play again ?") 
    if (playAgain) { 
     headsTails(); 
    } else { 
     alert("Thanks for playing!") 
    } 
} 
+0

謝謝,這已經解決了我關於這個問題的所有問題。 –