如果条件满足时语句不重复?

时间:2015-08-21 02:32:18

标签: javascript loops if-statement

我希望脚本继续提示用户输入0到100之间的有效输入,但无法使其正常工作。我比昨晚开始处理这个脚本时更困惑。这是我的作业,老师要求我们使用if语句,这就是为什么我还没有尝试使用while循环,但也许我应该这样做。

这是代码。



<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Grade</title>
  <script type="text/javascript">
    var grade = Number(prompt("What did you score: ", "Your Score Here!"));

    if (grade < 0 || grade > 100) {
      grade = Number(prompt("Please enter a valid score", "Your Score Here!"));
    } else if (grade >= 0 && grade < 60) {
      grade = "F";
    } else if (grade >= 60 && grade < 70) {
      grade = "D";
    } else if (grade >= 70 && grade < 80) {
      grade = "C";
    } else if (grade >= 80 && grade < 90) {
      grade = "B";
    } else if (grade >= 90 && grade <= 100) {
      grade = "A";
    }

    document.write("<strong>Your grade is:</strong> " + grade);
  </script>
</head>

<body>

</body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

是的,你会使用while循环。在这种情况下,您将有一个标志来检查输入是否无效。我们可以假设它在循环中有效,并且当无效检查通过时将其更改为无效(false),并导致循环重复。

&#13;
&#13;
<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Grade</title>
  <script type="text/javascript">
    var grade = Number(prompt("What did you scrore: ", "Your Score Here!"));
    var valid = false;
    while(!valid)
    {   
        valid = true; // assume it's valid
        if (grade < 0 || grade > 100) {
          grade = Number(prompt("Please enter a valid score", "Your Score Here!"));
          valid = false; // It it happens to not be valid, change it to invalid
        } else if (grade >= 0 && grade < 60) {
          grade = "F";
        } else if (grade >= 60 && grade < 70) {
          grade = "D";
        } else if (grade >= 70 && grade < 80) {
          grade = "C";
        } else if (grade >= 80 && grade < 90) {
          grade = "B";
        } else if (grade >= 90 && grade <= 100) {
          grade = "A";
        }
    }
    document.write("<strong>Your grade is:</strong> " + grade);
  </script>
</head>

<body>

</body>

</html>
&#13;
&#13;
&#13;