在下面的例子中 - 假设返回值没有任何重要性 - 是否有理由更喜欢任何一种方法而不是另一种方法?
// 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;
}
Run Code Online (Sandbox Code Playgroud)
似乎最佳实践(主要是我工作过的地方)是在方法或函数的顶部设置默认值,并且只有在出现某些条件时才更改这些值.因此,不需要使用else,因此方法2是优选的.
由于该示例是JavaScript,因此需要特别注意代码大小.因此,方法2将为相同的功能创建更少的代码,从而进一步将其参数作为首选.
但是,如果您有超过2个可能的条件,否则否则无法避免.但是,在这些情况下,我工作的大多数地方都更喜欢Switch Case.
| 归档时间: |
|
| 查看次数: |
23076 次 |
| 最近记录: |