使用伪登录表单并遇到if-else语句的问题。我创建了一个函数来检查提交时的对象数组,看它们是否与输入内的文本匹配。只有在找不到电子邮件输入时才应打印最后一个else语句。我发现删除了最后一个修复问题的其他声明,但如果没有匹配则无法打印'用户未找到'。很确定这是一个简单的修复,但我似乎无法找到错误。
如何在不删除最后一条else语句的情况下正常运行? (包括HTML以供参考。)
var logForm = document.querySelector("#logForm");
var output = document.querySelector("#output");
var users = [{
email: "email1@address.com",
password: "123"
}, {
email: "email2@address.com",
password: "123again"
}, {
email: "email3@address.com",
password: "123again2"
}];
var submitHandler = function(e) {
e.preventDefault();
output.innerText = '';
var inputEmail = logForm.email.value;
var inputPassword = logForm.password.value;
console.log(inputEmail);
console.log(inputPassword);
for (var i = 0; i < users.length; i++) {
if (inputEmail === users[i].email) {
if (inputPassword === users[i].password) {
output.innerHTML = "Successfully logged in as " + users[i].email;
} else {
output.innerHTML = "Invaild password.";
}
} else {
output.innerHTML = "User not found.";
}
}
};
logForm.addEventListener('submit', submitHandler);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login Form</title>
</head>
<body>
<p>
<form id="logForm">
<input type="text" name="email" placeholder="E-mail"></input>
<input type="text" name="password" placeholder="Password"></input>
<button type="submit">Log In</button>
</form>
</p>
<p id="output"></p>
</body>
</html>
答案 0 :(得分:3)
在阵列中找到用户后,您需要停止搜索。为此,您需要break
循环或只需从函数返回:
for (var i = 0; i < users.length; i++) {
if (inputEmail === users[i].email) {
if (inputPassword === users[i].password) {
output.innerHTML = "Successfully logged in as " + users[i].email;
} else {
output.innerHTML = "Invaild password.";
}
break;
} else {
output.innerHTML = "User not found.";
}
}
答案 1 :(得分:1)
解决问题的三件事:
声明一个布尔变量,让我们说userFound
,如果在for
循环中找到电子邮件输入,则将其设置为true。
在break
块结尾处使用if (inputEmail === users[i].email)
语句,以便在找到电子邮件输入后停止for
循环。
将output.innerHTML = "User not found."
移到for
循环之外,只有在userFound
等于false时才执行该语句。
以下是修改后的代码
var userFound = false;
for (var i = 0; i < users.length; i++) {
if (inputEmail === users[i].email) {
if (inputPassword === users[i].password) {
output.innerHTML = "Successfully logged in as " + users[i].email;
} else {
output.innerHTML = "Invalid password.";
}
userFound = true;
break; // stop the iteration
}
}
if (!userFound) {
output.innerHTML = "User not found."; // only do this if user isn't found
}