我尝试创建alert
询问用户电子邮件,以及它是否与存储的变量兼容,然后会显示一条警告,其中包含Logged!消息,但循环不能仅使用我的代码if
和else
,但只有一次。
//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();

答案 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)
str
不会更新。为此,我使用fiddle循环至少执行一次,并在用户未输入正确值时循环。 str++
,因为它没有任何意义来增加(do...while
)字符串值。 alert
内的连接更改为更简洁的内容。++
语句,因为它们会停止执行该函数,而这不是你想要的。
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();