我想检查用户和通行证是否匹配以及它们的索引,因为我使用对象数组,我使用 localstorage 和 javascript 进行此活动
//find user if exist
var founduser = accounts.find(e =>{
return e.user === user
})
//find pass if exist
var foundpass = accounts.find(e =>{
return e.pass === pass
})
//find index of user
var indexofuser = accounts.indexOf(founduser)
//find index of pass
var indexofpass = accounts.indexOf(foundpass)
//check if either 2 of them is undefined
if( foundpass != undefined || founduser != undefined){
//check if the index are matched
if( indexofuser === indexofpass){
alert("logged in successfully")
}
//return an alert if its not matched
else{
alert("Wrong Password Please try again")
}
}
//return an alert if on of it is undefined
else{
alert("Wrong Password Please try again")
}
您可以使用
.find()
,但只有当帐户的 user
和 pass
属性都匹配时,回调函数才返回 true:
const foundUser = accounts.find(e =>{
return e.user === user && e.pass === pass;
});
if (foundUser) {
alert("logged in successfully")
} else {
alert("Wrong Password Please try again")
}
这应该为您提供与现有代码相同的行为,因为您在两个
else
块中记录相同的内容。但是,请务必考虑以下一些安全隐患:
.find()
可能会让您面临定时攻击,让用户猜测用户名/密码是什么