计算输入javascript的次数

时间:2012-10-02 13:56:42

标签: javascript

在计算javascript中执行操作的次数时,最佳做法是什么?例如,我有一个要求输入数字的提示

 var playerGuess = prompt("What is your guess ");

我想做的是在3次尝试以另一个提示结束游戏后。

我遇到的困难实际上是计算输入数量

由于

我尝试过创建一个函数来计算输入的次数

    var guessCount = playerGuess.count;


   function limit(playerGuess){

  if (guessCount >= 3){
   alert("game over");
  } else{
   alert("carry on");
  }

 }

完全错了我知道但是去了

3 个答案:

答案 0 :(得分:1)

您应该评估每次获得的答案。 如果答案有效,请在另一个变量中取计数,当计数达到所需数量时,不要输入。

var attempts    = 0;

function ask_question(){

  if(attempts > 3)
  {
   // you have played enough!
   return;
  }
  else
  {

   var playerGuess = prompt("What is your guess ");

   if(parseInt(playerGuess) != NaN && playerGuess != '')
   {
    attempts++;
    // do whatever you would like to do with playerGuess
   }
  }
}

答案 1 :(得分:1)

像这样:

// Global var to hold number of guesses
var guessCount = 0;

// Function to get the guess
function getGuess() {
  // Get a new guess
  var guess = prompt('What is your guess ');

  // Process guess here, eg:
  if (...whatever tests you want to make...) {
    // Good guess
    alert('Good guess: ' + guess);

  } else {
    // Bad guess
    guessCount += 1;

    // Fail out if too many guesses have been tried
    if (guessCount >= 3) {
      alert('Game over');
      return;
    }
  }
};

干杯!

答案 2 :(得分:1)

您可以使用while循环和变量来存储当前迭代。请考虑以下内容,它为您提供三次机会来猜测“秘密”号码:

var secretNumber = 42,
    youWon = false,
    i = 0;

while (i < 3) {
  var playerGuess = prompt("What is your guess?");

  if (playerGuess == secretNumber){
    youWon = true;
    break;
  }

  i++;
}

if (youWon) {
  alert("You got it!");
} else {
  alert("Sorry, you have no more tries left.");
}

此代码反复循环,每次递增i。它询问问题,并检查答案。如果答案是正确的,它会将youWon标记和break设置为循环,并提前结束。否则,循环在3次迭代后自然结束。循环完成后,检查youWon标志以确定循环是否结束,因为给出了正确答案,或者是否因为尝试次数用尽而结束循环。