while循环中的if和else语句不起作用

时间:2017-10-05 13:57:16

标签: javascript loops

我尝试创建alert询问用户电子邮件,以及它是否与存储的变量兼容,然后会显示一条警告,其中包含Logged!消息,但循环不能仅使用我的代码ifelse,但只有一次。



//working code
function validation(str) {
  var str = prompt("Please Enter your email");
  var email = "plapla@gmail.com";

  if (str === email) {
    return alert("Welcome back, Logged Successfully!" + " your email is " + str);
  } else {
    return alert("Your Email is incorrect, Please Try again");
  }

}

validation();






//Loop Code
function validation(str) {
  var str = prompt("Please Enter your email");
  var email = "plapla@gmail.com";
  while (str !== email) {
    if (str === email) {
      return alert("Welcome back, Logged Successfully!" + " your email is " + str);
    } else {
      return alert("Your Email is incorrect, Please Try again");
    }
    str++;
  }
}

validation();




3 个答案:

答案 0 :(得分:1)

变量str未在循环中更新。您还使用了return语句,该语句将在第一次迭代后停止循环。

您需要在循环中使用prompt(""),并且继续此循环的条件为str !== email

如果来自提示的消息与电子邮件相同,则循环将停止并在while执行后进行编码

var str = prompt("Please enter your email");
var email = "test";

while (str !== email) {
  str = prompt("Please enter a valid email");
}

alert("Yeah ! Hello !");

答案 1 :(得分:1)

我相信这是你打算实现的目标



function validation() {
  var str = prompt("Please Enter your email");
  var email = "plapla@gmail.com";
  do {
    if (str === email) {
      alert("Welcome back, Logged Successfully!" + " your email is " + str);
    } else {
      str = prompt("Your Email is incorrect, Please Try again");
    }
  } while (str !== email)
}

validation();




答案 2 :(得分:0)

  1. 每次迭代时都必须获取值,否则str不会更新。为此,我使用fiddle循环至少执行一次,并在用户未输入正确值时循环。
  2. 我从您的代码中删除了str++,因为它没有任何意义来增加(do...while)字符串值。
  3. 我将alert内的连接更改为更简洁的内容。
  4. 我还删除了++语句,因为它们会停止执行该函数,而这不是你想要的。
  5. function validation() {
      do {
        var str = prompt("Please enter your email");
        var email = "plapla@gmail.com";
        
        if (str === email) {
          alert("Welcome back, Logged Successfully ! Your email is " + str);
        } else {
          alert("Your email is incorrect, please try again");
        }
      } while (str !== email) 
    }
    
    validation();