如何在条件成立后停止程序执行

时间:2015-03-20 17:26:13

标签: javascript function

我希望我的程序在条件成立后停止执行。我编写的代码根据随机生成的数字测试用户输入,如果猜测等于生成的数量我想阻止用户输入更多的值,而是收到一条消息告诉他们他们& #39;赢得了比赛。

我有一个简单的表单,用户输入他们的猜测并单击要提交的按钮。以下是我的功能:

function parseGuess(guess){

var diff = Math.abs(generatedNumber - guess);

    if(diff >= 50){
            view.displayMessage("Ice cold");

        } else if (diff >= 30 && diff < 50){
            view.displayMessage("Cold");

        } else if (diff >= 20 && diff < 30){
            view.displayMessage("Warm");

        } else if (diff >= 10 && diff < 20){
            view.displayMessage("Hot");

        } else if (diff >= 1 && diff < 10){
            view.displayMessage("Very hot");

        } else if(guess === generatedNumber){
            gameOver = true; 
         view.displayMessage("Well done! You guessed the number in " + (controller.guesses + 1)+" guesses");

        }

}

在用户单击按钮时调用的控制器对象内调用parseGuess:     var controller = {

        guesses: 0,

            processGuess: function(guess) {

            var count = document.getElementById("count");   

            //var diff = Math.abs(generatedNumber - guess); 



            console.log(gameOver);



            if (guess <=0 || guess >=101 || isNaN(guess) || guess == "")
                {   
                    return alert("Oops, please enter a number between 1 & 100");

                }


                parseGuess(guess); 
                this.guesses++;

                addListElement(guess); 
                count.innerHTML = this.guesses; //write the guess count into the span  


        return null;
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用return退出任何功能,例如:

function parseGuess(guess){

var diff = Math.abs(generatedNumber - guess);

    if(diff >= 50){
            view.displayMessage("Ice cold");
            return false;
    }
}

以下是您的示例背景中的小提琴: https://jsfiddle.net/theodin/0e4mso4L/1/