问题描述
在下面的例子中 - 假设返回值没有任何重要性 - 是否有理由偏向另一种方法?
In the following example - given that the return value isn't of any importance - is there a reason to prefer either method over the other?
// Method 1
function (a, b) {
if (a == b){
// I'm just interested in
// the stuff happening here
} else {
// or here
}
return true;
}
// Method 2
function (a, b) {
if (a == b){
// I'm just interested in
// the stuff happening here
return true;
}
// or here
return true;
}
推荐答案
这似乎是最佳做法(主要是我工作过的地方)是在方法或函数的顶部设置默认值,只有在出现某些条件时才更改这些值。因此,不需要使用else,因此方法2是优选的。
It seems that best practices (mostly by places I've worked for) is to set default values at the top of a method or function and only change those values if some condition occurs. Thus, the use of else is not needed so Method 2 is preferred.
由于示例是JavaScript,因此需要特别注意代码大小。所以方法2会为相同的功能创建更少的代码,进一步将其参数作为首选。
Since the example is JavaScript, special attention needs to be paid in regards to code size. So Method 2 would create less code for the same functionality, furthering its argument as the preferred.
但是,如果你有超过2个可能的条件,则为else或者if无法避免。但是,在这些情况下,我工作的大多数地方都更喜欢Switch Case。
However, if you have more than 2 possible conditions, an else or else if cannot be avoided. However, most places I've worked prefer a Switch Case in these situations.
这篇关于if..else vs if(){return}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!