我在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';
};
});
};
在这里,当我输入凭据:guido
和password
时,系统会提示登录不正确。但当我输入ben
和test
时,它将照常进行。如果任何人有一个想法,为什么这不能工作或有更好的代码,请留下答案。正如我所说的,这将被散列,加盐,而不是在文件中,当它工作时,所有这些东西。
发布于 2018-08-25 00:16:44
问题似乎是你没有跳出你的循环,所以你实际上是在检查数组中的所有元素,但最后一个元素是粘滞的。试着从你的循环中刹车,就像这样;
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循环来允许跳出循环。
https://stackoverflow.com/questions/52008220
复制相似问题