【发布时间】:2019-09-03 14:29:53
【问题描述】:
如果不绑定到一个变量,处理多个条件情况的最佳做法是什么?
例如我们可以使用else if 声明:
if (a && b > 10) {
...
} else if (a && b < 5) {
...
} else if (!a && c === 'test') {
....
} else if (!a && c === 'test2') {
...
} else {
...
}
这只是一个例子,所以不要试图通过重新组合逻辑来简化它。请注意,我们不能在这里使用简单的开关。我们也不能使用带有选项的地图。
作为替代方案,我们可以使用switch(true) 使其更具可读性:
switch(true) {
case (a && b > 10):
...
break;
case (a && b < 5):
...
break;
case (!a && c === 'test'):
...
break;
case (!a && c === 'test2'):
...
break;
default:
...
}
这是绝对合法的,并得到许多作者的推荐。但另一方面,许多开发人员不喜欢它,因为 true 语句不是变量而是常量。
我读过一些关于switch(true) 用法的帖子。如下:javascript switch(true)
在没有一个变量的情况下,对于这样的多个条件,最好的解决方案是什么?
解决方案: 我最终得到了 Erik Philips 答案的简化版本。谢谢埃里克!
let descriptionByType: {description: string, check: check: () => Boolean}[] = [
{ description: 'result 1', check: () => a && b > 10 },
{ description: 'result 2', check: () => a && b < 5 },
{ description: 'result 3', check: () => !a && c === 'test' },
{ description: 'result 4', check: () => !a && c === 'test2' },
{ description: 'default result', check: () => true },
];
return descriptionByType.find(x => x.check()).description;
它非常清晰和灵活。
【问题讨论】:
-
我会说,这是一个品味问题。我以前从未见过
switch (true)语法,实际上我认为这是 switch 语句的“怪异”用法,因为它很可能不打算以这种方式使用。我的偏好是坚持使用if-else if-else块。大多数开发工具也能够很好地折叠块,因此,如果您需要概览,您可以通过这种方式获得它。switch块折叠支持可能要少得多。 -
是的,
switch(true)绝对可怕,需要你处理失败。它比你意思的if/else链可读性差,并且欺骗了读者。 -
顺便说一句,你可以做
if (a) { if (b > 10) { … } else if (b < 5) { … } } else { if (c == 'test) { … } else if (c == 'test2') { … } }(如果你看到优势,你可以在c上switch) -
Christoph Herold,我们可以用花括号将箱体包裹起来,然后就可以折叠了。如果箱体很大,这很有用。
-
这似乎是一个意见问题或链接问题的完全相同。我们应该在这里做什么?
标签: javascript typescript if-statement switch-statement