多维javascript数组,仅会影响forEach

时间:2018-08-24 16:11:21

标签: javascript arrays

我在JavaScript中有一个多维数组,其中包含基本的用户名和将要散列的密码。目前,当调用检查凭据的功能时,forEach将仅检查最后一个数组。

const titleText = document.getElementById('loginText');
const usernameField = document.getElementById('usernameField');
const passwordField = document.getElementById('passwordField');

const usernames = [['guido','password'],['ben','test']];

function checkCreds() {
    titleText.textContent = ">> Checking login";

    usernames.forEach(element => {
        if (element[0] === usernameField.value) {

            if (element[1] === passwordField.value) {

                titleText.textContent = '>> Login Valid';
                window.location = "dashboard.html";

            } else {
                titleText.textContent = '>> Password incorrect';
            };
        } else {
            titleText.textContent = '>> Login incorrect';
        };
    });
};

在这里,当我输入凭据guidopassword时,会说登录不正确。但是当我键入bentest时,它将照常进行。如果有人对为什么这种方法行不通或有更好的代码有想法,请放弃答案。正如我说的那样,它将在工作时被散列,加盐,而不是文件中的所有内容。

1 个答案:

答案 0 :(得分:4)

问题似乎是您没有中断循环,因此实际上您正在检查数组中的所有元素,但最后一个元素是要粘贴的元素。尝试从循环中刹车,类似这样;

const titleText = document.getElementById('loginText');
const usernameField = document.getElementById('usernameField');
const passwordField = document.getElementById('passwordField');

const usernames = [
  ['guido', 'password'],
  ['ben', 'test']
];

function checkCreds() {
  titleText.textContent = ">> Checking login";

  // instead of using Array.forEach use a standard for loop, this allows you to
  // break out of the loop and return. 
  for(let i = 0; i < usernames.length; i++){
    if (usernames[i][0] === usernameField.value){
      if (usernames[i][1] === passwordField.value){
        // show that the login was successful
        titleText.textContent = '>> Login Valid';
        // redirect to the dashboard
        window.location = 'dashboard.html';
        // just return here, there is no need to break out of the loop,
        // returning will end the execution of this function.
        return;
      }
    }
  }
  
  // display the error to the user, we don't want to indicate if the 
  // password or the username were invalid because that tells an attacker
  // they have the correct user name.
  // We also don't have to check a flag because a valid login will result
  // in this code never being hit
    titleText.textContent = '>> Login incorrect';
};

编辑:

根据本·韦斯特(Ben West)的信息,我更新了解决方案,以使用标准的for循环以允许脱离循环。