0

计算在 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");
  }

 }

我知道完全错了,但试一试

4

3 回答 3

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
   }
  }
}
于 2012-10-02T13:59:13.697 回答
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;
    }
  }
};

干杯!

于 2012-10-02T14:03:54.330 回答
1

您可以使用while循环和变量来存储当前迭代。考虑以下内容,这使您有 3 次机会猜测“秘密”数字:

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标志和breaks 退出循环,提前结束。否则,循环在 3 次迭代后自然结束。循环完成后,youWon检查标志以确定循环是否因为给出正确答案而结束,或者是否因为尝试次数用尽而结束。

于 2012-10-02T14:09:48.393 回答