在可读性之外使用 if...else 是否有好处?
例如,如果我有一个函数:
function a(b){
if(b=="c"){
return true
}else{
return false
}
}
我不能把它压缩得更像这样吗:
function a(b){
if(b=="c"){
return true
}
return false
}
return false 不会触发,只要 b=="c",但它不需要 else 语句。
我遇到过很多次,我总是选择更精简的版本(主要是为了省去写更多)。对于像这样的示例,是否有理由包含 else 语句而不是为了提高可读性?
最佳答案
通常 return
之后的 else
被认为是多余的,但是,当“yes”和“no”分支在某种意义上相似时,最好将它们保持在同一位置缩进水平,为了对称。比较:
// confusing
if (spam.exists()) {
$(box).content = "Spam already exists";
$(button).disable();
return failure;
}
$(box).content = "Added new spam";
$(button).enable();
return success;
和
// less confusing
if (spam.exists()) {
$(box).content = "Spam already exists";
$(button).disable();
return failure;
} else {
$(box).content = "Added new spam";
$(button).enable();
return success;
}
关于javascript - 如果 IF 语句结束函数,为什么要使用 IF...ELSE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13083359/