JavaScript检查一个对象数组的结果是错误的,而它应该是真的

JavaScript checking an array of objects is coming up false when it should be true

本文关键字:真的 错误 一个对象 检查 数组 结果是 JavaScript      更新时间:2023-09-26

处理伪登录表单时遇到if-else语句的问题。我创建了一个函数,在提交时检查对象数组,看看它们是否与输入中的文本匹配。只有在找不到电子邮件输入的情况下,才应该打印最后一个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>

一旦在数组中找到用户,就需要停止搜索。为此,您需要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.";
    }
}

演示:http://jsfiddle.net/5mfaoz9e/1/

解决问题的三件事:

  1. 声明一个布尔变量,比如userFound,如果在for循环中找到电子邮件输入,则将其设置为true。

  2. 一旦找到电子邮件输入,请在if (inputEmail === users[i].email)块末尾使用break语句来停止for循环。

  3. 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
}

演示:http://jsfiddle.net/rjdxxvmk/