提问人:Yixing Wang 提问时间:1/22/2023 更新时间:1/22/2023 访问量:47
JavaScript 意外的未定义值 [已关闭]
JavaScript unexpected undefined value [closed]
问:
我正在运行以下 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(“ace的登录:” + validCredentials(“ace”,“错误”));返回 false,但它返回 undefined。谁能告诉我出了什么问题?
答:
1赞
Unmitigated
1/22/2023
#1
您不会在所有可能的分支中返回(即,如果用户名存在,但密码不正确)。将 外部移动到函数中的最后一个语句。return false
else
或者,您可以将 和 的链简化为一个语句:if
else
return usernames.includes(enteredUsername) &&
passwords[usernames.indexOf(enteredUsername)] === enteredPassword;
评论
0赞
Arvind Kumar Avinash
1/23/2023
这个答案引导人们朝着正确的方向前进。
评论
if(enteredPassword == correctPassword) { return true; }
没有返回 false 的对应项else