簡體   English   中英

如何擺脫這個循環

[英]How to get rid of this loop

我用 JS 開發了一個簡單的登錄系統。 當密碼、用戶名或兩者都不正確時,它應該顯示警報,但現在顯示 4。我知道這是因為 for 循環,但我不知道如何在不破壞所有代碼的情況下擺脫它。 提前致謝 =)

我把這段代碼留在這里:

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");
        }
      }
    }

添加break; 在每個 document.write 或 alert 語句之后。

如果一個帳戶的用戶名錯誤,您不想告訴他們他們的帳戶不存在,直到您檢查每個帳戶:

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.");
}

您的直覺是正確的,for 循環在這里可能並不理想。 它很難閱讀和調試,而且有點難看。 如果您想堅持下去,其他答案會告訴您如何做。

假設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