gpt4 book ai didi

javascript - 这种 if/else 编程习惯不好吗?

转载 作者:行者123 更新时间:2023-11-28 19:01:02 25 4
gpt4 key购买 nike

我在一个函数中有这个 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 更好。 (然后您可以将该行读作“else if(not)passwords(don't)match”。)

关于javascript - 这种 if/else 编程习惯不好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32537458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com