本文介绍了如何减少JavaScript中if语句中的多个OR条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个条件:
if (item == 'a' || item == 'b' || item == 'c' || item == 'd' || item == 'e') {
// statements
}
如何减少分支?还有其他方法可以用JavaScript编写吗?
How can I reduce the branching? Is there any other way to write this in JavaScript.
推荐答案
您还可以使用更新的 Array.includes
You can also use the newer Array.includes
if (['a','b','c','d','e'].includes(item)) {
...
}
另一个选择(对于您所发布的非常特殊的情况)是使用<
/>
Another option (for the very specific case you posted) would be to compare unicode point values using <
/>
if (item >= 'a' && item <= 'e') {
...
}
这篇关于如何减少JavaScript中if语句中的多个OR条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!