我可以使用while循环来验证提示输入吗?

时间:2018-01-23 20:54:15

标签: javascript

我正在Javascript课程中完成一个项目,我需要检查条件以确保传递正确的信息。

我正在努力学习像程序员一样思考所以我的第一个解决方案只检查了一次条件。看到这是一个问题,我试图想办法继续检查条件,直到所有信息都正确。我正在尝试使用while循环,但我无法使其正常工作。

我的逻辑只要lastname不等于NaN OR lastname.value少于4 char long或lastname等于null。继续要求姓名。如果这些条件中的任何一个都是真的,请继续询问姓氏,直到它们都是假的。

我想使用while循环进行性别提示,但我不确定我在做什么。

我是新手,并不确定我在哪里出错?

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Conditionals</title>
    <script>
    /*
    Write the greetUser() function that prompts the user
    for his/her gender and last name and stores the results
    in variables.

    For gender:
        If the user enters a gender other than "Male" or "Female",
        prompt him/her to try again.

    For last name:
        If the user leaves the last name blank, prompt him/her to
        try again.
        If the user enters a number for the last name, tell the user
        that a last name can't be a number and prompt him/her to try again.

    After collecting the gender and last name...
        If the gender is valid, pop up an alert that
        greets the user appropriately (e.g, "Hello Ms. Smith!")
        If the gender is not valid, pop up an alert
        that reads something like "XYZ is not a gender!"
    */




    function greetUser() {
        var gender, lastname;

        gender = prompt("are you a Male or Female? ");

        if (gender != "Male" && gender != "Female") {
            gender = prompt("Try again: Male or Female?");
        }

        lastname = prompt("And what is your last name?")

        while (lastname != NaN || lastname.value < 4  lastname == null); {

            lastname = prompt("Please try again. What is your last name?");
       }

    }







    </script>
    </head>
    <body onload="greetUser();">
        <p>Nothing to show here.</p>
    </body>
    </html>

1 个答案:

答案 0 :(得分:2)

&#13;
&#13;
function greetUser() {
  var gender, lastname;

  gender = prompt("are you a Male or Female? ");
  while (gender !== "Male" && gender !== "Female") {
    gender = prompt("Try again: Male or Female?");
  }

  lastname = prompt("And what is your last name?")
  while (lastname === '' || lastname.length < 4 || lastname === null) {
    lastname = prompt("Please try again. What is your last name?");
  }
}

greetUser();
&#13;
&#13;
&#13;

我对你的代码做了一些修改。

  • 你的while循环有不正确的逻辑运算符,这是正确的版本:while (lastname === '' || lastname.length < 4 || lastname === null)此外,你正在比较lastname !== ''
  • 对于性别提示,您需要执行while循环while (gender !== "Male" && gender !== "Female")

希望有所帮助!