JavaScript validCredentials函数返回undefined问题:预期返回false却异常
为什么validCredentials函数在用户名存在但密码错误时返回undefined?
先看你提供的代码:
// 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
问题原因
你的函数存在分支覆盖不全的问题:
- 当用户名不存在时,会进入
else分支返回false,这部分逻辑正常。 - 当用户名存在但密码不匹配时,内层的
if(enteredPassword == correctPassword)条件不成立,此时函数没有任何return语句执行,JavaScript函数在没有显式返回值时会默认返回undefined,这就是你看到的异常结果。
修复方案
调整逻辑确保所有分支都有明确的返回值,比如简化成如下形式:
function validCredentials(enteredUsername, enteredPassword) { let usernames = ["smith", "tron", "ace", "ladyj", "anon"]; let passwords = ["qwerty", "EndOfLine", "year1942", "ladyj123", "PASSWORD"]; if (usernames.includes(enteredUsername)){ const correctPassword = passwords[usernames.indexOf(enteredUsername)]; // 直接返回密码匹配结果,匹配为true,不匹配为false return enteredPassword === correctPassword; } // 用户名不存在直接返回false return false; }
这样不管是用户名不存在,还是用户名存在但密码错误,都会返回false,完全符合预期逻辑。
内容的提问来源于stack exchange,提问作者Yixing Wang
相关产品推荐
相关产品推荐

