简体   繁体   English

如何摆脱这个循环

[英]How to get rid of this loop

I've developed a simple login system in JS.我用 JS 开发了一个简单的登录系统。 When the password, the username or both are incorrect it's suposed to show an alert but now it shows 4. I know it is because of the for loop but I don't know how to get rid of it without breaking all the code.当密码、用户名或两者都不正确时,它应该显示警报,但现在显示 4。我知道这是因为 for 循环,但我不知道如何在不破坏所有代码的情况下摆脱它。 Thanks in advance =)提前致谢 =)

I leave here the piece of code:我把这段代码留在这里:

function getName() {
      var user = document.getElementById('Username').value;
      var pass = document.getElementById('Password').value;
      
      for (let f = 0; f < arr.length; f++) {
        if (user == arr[f][0] && pass == arr[f][1]) {              
          document.write("Welcome back ", user, ", we've missed you");
        }
        if (user == arr[f][0] && pass != arr[f][0])  {
          alert("Your password is incorrect");
        }
        else if (user != arr[f][0] && pass == arr[f][1]) {
          alert("Your username is incorrect");
        }
        else {
          alert("Unnexistant account");
        }
      }
    }

Add break;添加break; after each document.write or alert statements.在每个 document.write 或 alert 语句之后。

If the username for one account is wrong, you don't want to tell them their account doesn't exist until you check it for every single account:如果一个帐户的用户名错误,您不想告诉他们他们的帐户不存在,直到您检查每个帐户:

function getName() {
    var user = document.getElementById('Username').value;
    var pass = document.getElementById('Password').value;

    for (let f = 0; f < arr.length; f++) {
        if (user == arr[f][0] && pass == arr[f][1]) {              
            document.write("Welcome back ", user, ", we've missed you");
            return; // exit from the function since we've found an account
        }
        if (user == arr[f][0] && pass != arr[f][0])  {
            alert("Your password is incorrect");
            return; // exit from the function since we've found a username match
        }
    }
    // couldn't find match, alert
    alert("Your account does not exist.");
}

Your instinct is correct, and a for loop is probably not ideal here.您的直觉是正确的,for 循环在这里可能并不理想。 It is hard to read and debug and it's also kind of ugly.它很难阅读和调试,而且有点难看。 If you want to stick with it, the other answers show you how.如果您想坚持下去,其他答案会告诉您如何做。

Assuming arr is an array of usernames & passwords, you can convert this into a Map and remove your loop completely.假设arr是一组用户名和密码,您可以将其转换为Map并完全删除循环。

const map = new Map();
arr.map(e => m.set(e[0], e[1]));

try {
  if (map.get(user) === pass) {
    document.write("welcome back " + user + ", we missed you.");
  } else {
    // although this might be too much info from a security standpoint.
    document.write("incorrect password"); 
  }
} catch (e) {
  document.write("could not find user.");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM