【问题标题】:How do I properly nest while and for loops in javascript如何在javascript中正确嵌套while和for循环
【发布时间】:2014-03-14 01:05:54
【问题描述】:

刚刚学习 javascript 并且很难使用此代码,希望让它重复 5 次不同的随机数学问题,但只有在回答正确的情况下才能继续下一个问题。有人可以帮我指出正确的方向吗?

// var initialization
var num1 = Math.floor(Math.random()*100)+1;
var num2 = Math.floor(Math.random()*100)+1;
var correct = num1 + num2;
var guess = 0;
var count = 1;
var msg = " ";
//var debug = 5;

// loop basic math process

while(count <= 1){

guess = eval(prompt("What is "+num1+" + "+num2+" = __ ?"));

    if(guess != correct){
        msg = alert("Sorry please try again");

    }else{
        msg = alert("By George I think you got it!");

        for(i=0;i<=5;i+=1){
            alert(debug);
            var num1 = Math.floor(Math.random()*100)+1;
            var num2 = Math.floor(Math.random()*100)+1;
            var correct = num1 + num2;

            guess = eval(prompt("What is "+num1+" + "+num2+" = __ ?"));

        if(guess != correct){
            alert("Sorry please try again");

        }else{
            alert("Great your on a roll!");

        }}} count++;
}

【问题讨论】:

  • count++ 放在else 条件中alert('Great you're on a roll!) 之后。
  • 感谢您的快速回复。
  • 使用console.log()作为调试输出;它远远优于警报(可以在一个好的浏览器中直接显示项目、元素等,而不仅仅是可怕的Object [object]。就此而言,也可以使用错误控制台查看错误消息!您发布的代码运行良好 - 如只要我修复了alert(debug),它会在 chrome 中引发错误。
  • eval 应该像瘟疫一样被避免,直到你有足够的经验来聪明地反对那个立场。如以下示例所示,您根本不需要评估 prompt() 的结果。您的代码具有评估我在答案中输入的任何表达式的有趣副作用 - 最有趣的是,如果它问我总和是多少,我可以直接输入 12 + 45,它会评估加法,我什至没有做数学!你几乎从来没有,几乎从来不需要eval

标签: javascript if-statement for-loop while-loop


【解决方案1】:

如果您想继续提问直到他们回答正确,那么您将需要两个循环。一算5题。其中一个是不断提出问题,直到它是正确的,我认为你的循环有点倒置。我会改为执行以下操作:

for(i=0;i<=5;i+=1){
    alert(debug);
    var num1 = Math.floor(Math.random()*100)+1;
    var num2 = Math.floor(Math.random()*100)+1;
    var correct = num1 + num2;
    var guess = -1;

    while (guess != correct) {    
        guess = eval(prompt("What is "+num1+" + "+num2+" = __ ?"));
        if(guess != correct){
            msg = alert("Sorry please try again");
        }else{
            msg = alert("By George I think you got it!");
        }
    }
}

如果您想知道他们是否连续多次正确更改消息,您必须检测他们是否处于连续状态:

var streak = 0;


    while (guess != correct) {    
        guess = eval(prompt("What is "+num1+" + "+num2+" = __ ?"));
        if(guess != correct){
            msg = alert("Sorry please try again");
            streak = 0;
        }else{
            streak++;
            if (streak < 2) {
                msg = alert("By George I think you got it!");
            } else {
                msg = alert("Keep up the good work!");
            }
        }
    }

【讨论】:

    【解决方案2】:

    根据您的编码,我想您不需要外部 while 循环。 如果您确实需要 while 循环来控制 for 循环的总轮数,则最好将整个 for 循环代码包装在一个单独的函数中。

    【讨论】:

      【解决方案3】:

      作为一个提示——如果你的编辑器没有能力重新格式化/重新缩进源代码,jsbeautifer.org 做得很好。

      var num1;
      var num2;
      var guess;
      var correct;
      var msg;
      
      // Bonus
      // It looked like you were trying to give different responses so it wasn't 
      // quite as boring
      
      var successMessages = [
        "Way to go!",
        "Alright!",
        "Cheers!",
        "Tally ho!"
        "Well done, old boy"
      ];
      
      var questionsLeft = 5;
      
      // loop basic math process
      while (questionsLeft !== 0) {
      
        num1 = Math.floor(Math.random() * 100) + 1;
        num2 = Math.floor(Math.random() * 100) + 1;
        correct = num1 + num2;
      
        guess = prompt("What is " + num1 + " + " + num2 + " = __ ? ");
        guess = parseInt(guess, 10); // Convert to a number
      
        if (guess !== correct) {
          msg = alert("Sorry please try again ");
        } else {
          msg = successMessages[questionsLeft];
          questionsLeft--;
        }
      }
      

      或者,如果你想让他们重复这个问题:

      var num1;
      var num2;
      var guess;
      var correct;
      var msg;
      var isRight;
      
      // Bonus
      // It looked like you were trying to give different responses so it wasn't 
      // quite as boring
      
      var successMessages = [
        "Way to go!",
        "Alright!",
        "Cheers!",
        "Tally ho!"
        "Well done, old boy"
      ];
      
      var questionsLeft = 5;
      
      // loop basic math process
      while (questionsLeft !== 0) {
      
        num1 = Math.floor(Math.random() * 100) + 1;
        num2 = Math.floor(Math.random() * 100) + 1;
        correct = num1 + num2;
      
        // They haven't answered yet, so they can't be right.
        isRight = false;
      
        while (!isRight) {
          guess = prompt("What is " + num1 + " + " + num2 + " = __ ? ");
          guess = parseInt(guess, 10); // Convert to a number
      
          isRight = guess !== correct
      
          if (isRight) {
            msg = alert("Sorry please try again ");
          } else {
            msg = successMessages[questionsLeft];
            questionsLeft--;
          }
        }
      }
      

      【讨论】:

      • 是的,我仍然熟悉 sublimetext 编辑器。感谢您的建议,下次我在这里发帖时,我会尝试 jsbeautifer.org。
      【解决方案4】:

      试试这个:

      var num1 = [], num2 = [], correct = [], count = 0, guess;
      for(var i=0; i<5; i++){
        num1[i] = Math.floor(Math.random()*101);
        num2[i] = Math.floor(Math.random()*101);
        correct[i] = num1[i]+num2[i];
      }
      while(count < 5){
        quess = prompt('What is '+num1[count]+'+'+num2[count]+' ?');
        if(+quess === correct[count]){
          alert('You are Correct!');
          if(++count === 5)alert('You Have Completed All of the Answers Correctly!!!');
        }
        else{
          alert('Please Try Again.')
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-05-27
        • 2023-03-02
        • 2020-10-09
        • 2013-10-26
        • 1970-01-01
        • 2022-01-26
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        相关资源
        最近更新 更多