JavaScript未定义的值



我正在运行以下JavaScript代码:

// Return true if the given username and password are in the database,
// false otherwise.
function validCredentials(enteredUsername, enteredPassword) {

// Database of usernames and passwords
let usernames = ["smith",  "tron",      "ace",      "ladyj",    "anon"];
let passwords = ["qwerty", "EndOfLine", "year1942", "ladyj123", "PASSWORD"];

// Search the usernames array for enteredUsername 

// Only return true if the enteredUsername is in username, and the
// same location in passwords is enteredPassword
if (usernames.includes(enteredUsername)){
var correctPassword = passwords[usernames.indexOf(enteredUsername)];
if(enteredPassword == correctPassword){
return true;
}    
}
else {
return false;
}  
}

console.log("Login for ladyj: " + validCredentials("ladyj", "ladyj123"));  // true
console.log("Login for ace: " + validCredentials("ace", "wrong"));  // false
console.log("Login for jake: " + validCredentials("jake", "???"));  // false

我正在等待console.log("Login for ace: "+ validCredentials("正确", "错误"));返回false,但返回undefined。谁能告诉我哪里出错了?

您不返回所有可能的分支(即,如果用户名存在,但密码不正确)。将return false移到else之外,作为函数中的最后一条语句。

或者,您可以将ifelse链简化为一个语句:

return usernames.includes(enteredUsername) && 
passwords[usernames.indexOf(enteredUsername)] === enteredPassword;

相关内容

  • 没有找到相关文章

最新更新