如何让我的if语句停止重复?

时间:2015-11-01 02:39:04

标签: javascript

好的,所以我正在创建一个小程序来猜测用户有多少手指,但只有5个手指是手指的最大数量。因此,如果用户点击高于5的数字,它应该提示说它没有检查更高但是当它确实提示警报重复并重复

如何阻止它重复?还请解释一下它为我重复的原因。

https://jsbin.com/hiniqiqobe/1/edit?html,js,output

//如果您输入的数字超过5,则会重复警告框

原始代码:

      <!DOCTYPE html>
<html>
<head>
<style>

</style>
</head>
<body>


<p>How many fingers are you holding up</p>
<input id="myNumber">
<button id="theGuess">Guess</button>

  <script type="text/javascript">
  document.getElementById("theGuess").onclick=function(){

    var gotit = false;  var guesses = 1;    var x; var outOfControl = 6;
    while(gotit == false){
               x = Math.random();
               x = 6*x;
               x = Math.floor(x);

                if (document.getElementById("myNumber").value==x){



                 gotit=true;

                }else{

                guesses++;

                }
                if (document.getElementById("myNumber").value >= outOfControl){

                    alert("sorry i can only guess up to five");
                }
          }
          alert("i got it "+x+".it only tool me"+guesses+" guesses" );
  }

  </script>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

&#13;
&#13;
document.getElementById("theGuess").onclick = function() {

  var gotit = false;
  var guesses = 1;
  var x;
  var outOfControl = 6;
  while (gotit == false) {
    x = Math.random();
    x = 6 * x;
    x = Math.floor(x);

    if (document.getElementById("myNumber").value == x) {



      gotit = true;

    } else {

      guesses++;

    }
    if (document.getElementById("myNumber").value >= outOfControl) {

      alert("sorry i can only guess up to five");
      return;
    }
  }
  alert("i got it " + x + ".it only tool me" + guesses + " guesses");
}
&#13;
&#13;
&#13;

添加&#39;返回&#39;在抱歉警报之后

假设你的循环运行直到gotit不为真。该脚本显示警报但不会从while循环中转义。

答案 1 :(得分:2)

实际上发生的事情是 你宣布gotit = false 并且您没有更新导致无限循环的gotit的值

你可以像@Lucky Chingi的回答中所建议的那样阻止无限循环