问题描述
我有一个JS if / else问题。我能知道为什么,如果输入正确的用户名和密码,还执行else语句吗?
如果正确,如果用户名和密码正确,则仅执行if语句。两者为何被处决? 代码如下:
var database = [
{
username: "john83reuben",password: "12345"
},{
username: "jdominic",{
username: "johnreuban",password: "12345"
}
];
newsFeed =[
{ username: "john83reuben",timeline: "Psalm 118:19. I will extol the Lord at all times; His praise will always be on my lips"},{ username: "jdominic",timeline: "Psalm 34:1-3. I thank you,Lord,with all my heart; I sing praise to you before the gods."},{ username: "johnreuban",timeline: "Psalm 138: 1-2. I will give thanks to the Lord because of his righteousness;"}
];
function signIn(user,pass){
for(let i=0; i < database.length ; i++){
if(database[i].username === user && database[i].password === pass ){
console.log(newsFeed);
}else{
console.log("Error");
}
}
}
var usernamePrompt = prompt("What is your username?");
var passwordPrompt = prompt("What is your password?");
signIn(usernamePrompt,passwordPrompt);
解决方法
您正在检查database
var的整个列表,当它与不具有正确凭据的项目匹配时,它将执行else情况,以避免在您使用时打破循环找到正确的一个
使用Array.prototype.some
方法来确定您的用户/密码是否至少匹配一次。
var result = database.some(item => {
return item.userName === user && item.password === pass
})
console.log(result)