首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >只影响forEach中最后一个数组的多维javascript数组

只影响forEach中最后一个数组的多维javascript数组
EN

Stack Overflow用户
提问于 2018-08-25 00:11:21
回答 1查看 68关注 0票数 2

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

代码语言:javascript
复制
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时,它将照常进行。如果任何人有一个想法,为什么这不能工作或有更好的代码,请留下答案。正如我所说的,这将被散列,加盐,而不是在文件中,当它工作时,所有这些东西。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-25 00:16:44

问题似乎是你没有跳出你的循环,所以你实际上是在检查数组中的所有元素,但最后一个元素是粘滞的。试着从你的循环中刹车,就像这样;

代码语言:javascript
复制
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循环来允许跳出循环。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52008220

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档