警报在运行代码时显示错误消息

时间:2016-06-29 19:50:43

标签: javascript

我正在关注Teamtreehouse上的Javascript轨道并尝试制作游戏。它要求用户猜测1到6之间的数字。用户可以猜出数字,输入较小的数字并获得另一个机会,输入更大的数字并获得另一个机会或根本不猜它。

var correctGuess = false;
    var randomNumber = Math.floor(Math.random() * 6) +1;
    var guess = prompt("I am thinking of a number between 1 and 6. What is it?");

    if (parseInt(guess) === randomNumber) {

        correctGuess = true;}

        else if (parseInt(guess) < randomNumber) {
            var guessMore = prompt("Try again! The value I am thinking of is lower than " + guess);
            if (parseInt(guessMore) === randomNumber ) { 
                correctGuess =true;}

        } else if (parseInt(guess) > randomNumber) {
            var guessLess = prompt("Try again! The number I am thinking of is smaller than " + guess);
            if (parseInt(guessLess) === randomNumber) {

                correctGuess = true; }
            }


        if ( correctGuess) {


            alert("Yey!");
        } else {
            alert("Better luck next time! The number was " + randomNumber);
        };

虽然代码对我来说似乎很好,但每次我们的5次(让我们说)显示异常(虽然用户猜到了数字,但它运行了else语句;或者它要求你较小的数字只是为了发现结果实际上是一个更大的数字等)。您必须运行几次运行代码才能看到我的意思https://jsfiddle.net/Cilvako/7yhhfv6g/。我做错了什么?

1 个答案:

答案 0 :(得分:1)

所以问题在于:

  

或它只是要求你找一个较小的数字才能找到结果   实际上是一个更大的数字等)

这是因为你有两个&#34;低于&#34;和&#34;小于&#34;在您的条件声明中。我改变了#34;低于&#34;到&#34;大于&#34;。

   else if (parseInt(guess) < randomNumber) {
            var guessMore = prompt(
            "Try again! The value I am thinking of is greater than " + guess);
            if (parseInt(guessMore) === randomNumber ) { 
                correctGuess =true;}
    } 
   else if (parseInt(guess) > randomNumber) {
            var guessLess = prompt(
            "Try again! The number I am thinking of is smaller than " + guess);
            if (parseInt(guessLess) === randomNumber) {

                correctGuess = true; }
            }

https://jsfiddle.net/7yhhfv6g/4/