我在函数中有这个if / else循环,我只想知道这是否是一种“可接受的”处理方式。它确实实现了我想要的功能,但是我认为必须有一个更优雅的解决方案。
var signUpCheckAll = function(username, password, passwordconf, email){
if (emptyChecker(username, password)) {
if (emptyChecker(passwordconf, email)) {
if (lengthChecker(password)) {
if (passwordCheck(password, passwordconf)) {
return true;
}
else{
console.log("Passwords don't match!");
}
}
else{
console.log("Password isn't long enough!");
}
}
else{
console.log("Some fields are empty!");
}
}
}
谢谢
最佳答案
我个人(可能还有许多其他人)认为这更具可读性:
if (!emptyChecker(username, password)) {
console.log("Some fields are empty!");
}
else if (!emptyChecker(passwordconf, email)) {
//Where’s the message?
}
else if (!lengthChecker(password)) {
console.log("Password isn't long enough!");
}
else if (!passwordCheck(password, passwordconf)) {
console.log("Passwords don't match!");
}
else {
return true;
}
我还建议重命名您的功能。目前尚不清楚函数名称
passwordCheck
的作用。函数名称应始终包含表示该函数的动作或返回的动词。 passwordsMatch
更好。 (然后,您可以将该行读为“否则(如果)(不)密码(不)匹配)”。)