简体   繁体   English

Javascript:函数内的函数

[英]Javascript: Function within a function

Is there any reason why this code isn't working? 有什么原因导致此代码无法正常工作? I have put the entire script into a function for the sake of the playAgain variable (see bottom) which would restart the function. 我出于playAgain变量(请参阅底部)的考虑将整个脚本放入函数中,该变量将重新启动该函数。 Any help would be much appreciated. 任何帮助将非常感激。

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!")
    }
}

You have many syntax errors: 您有许多语法错误:

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

I would recommend reading about Javascript and in general about programming languages... 我建议阅读有关Javascript以及有关编程语言的一般文章...

Corrected headsTails function: 更正的headTails功能:

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!")
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM