【发布时间】:2021-01-05 01:58:12
【问题描述】:
我最近参加了一场代码语法格式辩论,并希望获得更广泛的 JavaScript 社区的意见。对于复杂的条件树,我个人更喜欢这种 switch/case 结构,但其他开发人员似乎不喜欢它。下面我将发布我喜欢的 switch/case 结构和 if/else 等效项。
而不是辩论偏好,为什么这个 switch/case 代码可以接受或不可接受以及具体原因?如果其他选择更好,为什么?
// My preferred switch/case block
switch (true) {
case testA() : return 'A';
case testB() || testG() : return 'B';
case testC() : return 'C';
case testA() && !testB() : return 'ZETA';
case a === b && c !== d : return 'foo';
default : return 'bar';
}
// if-else alternate #1
if (testA()) {
return 'A';
}
if (testB() || testG()) {
return 'B';
}
if (testC()) {
return 'C';
}
if (testA() && !testB()) {
return 'ZETA';
}
if (a === b && c !== d) {
return 'foo';
}
return 'bar';
// if-else alternate #2
if (testA()) return 'A';
if (testB() || testG()) return 'B';
if (testC()) return 'C';
if (testA() && !testB()) return 'ZETA';
if (a === b && c !== d) return 'foo';
return 'bar';
【问题讨论】:
-
它们都有效。我几乎总是讨厌使用
switch,但这看起来很合理(可能是我见过的switch最合理的用法之一)。下部的另一种替代方法是删除elses,因为它们在returns 之后是多余的。另一件要考虑的事情是,如果首先将test调用保存在变量中可能会很好,而不是可能多次重新测试同一件事。 -
你说得很好。我将使用您的建议更新代码示例中的 if-else 结构,因为我不希望这会分散问题的重点。函数调用旨在表示计算属性或多个其他条件的组合。
-
一旦您从替代 #1 中删除 else,现在您拥有的是替代 #2,只需使用额外的工件和线条。
标签: javascript syntax