Javascript - 带有 shorthand 表示法的多个条件的 if 语句

Javascript - if statement with several conditions in shorthand notation

我的脚本中有几个 if 语句需要很多条件,我想以更有效的方式编写它们,并使用 "shorthand notation" 以提高可读性。

例如,我有这个 if 语句:

if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    /*** some code ***/
}

所以我用 indexOf 和 array 写了它,但我不确定这是否是最好的方法:

if (['abc', 'def', 'ghi' ,'jkl'].indexOf(x) > -1) {
   /*** some code ***/
}

我几乎可以肯定还有其他一些方法更干净、速度更快...

这真是一个可读性的问题。当您在五个月内阅读相同的代码时,什么最有意义?

x === 'a' || x === 'b' || x === 'c' || x ==='d'

['a', 'b', 'c' ,'d'].indexOf(x) > -1

我会使用长 'or' 表达式,因为它非常清楚明确地告诉您代码在做什么。但是,我将该表达式包装在一个函数中,以使其余代码更具可读性

示例:

isSpecialLetter = function (x){
  return x === 'a' || x === 'b' || x === 'c' || x ==='d';
}

if(isSpecialLetter(x)){
//More code
}

您的数组可读且易于修改。如果您以后选择这样做,它还使您能够将数组作为参数。

如果您使用的是 ES6,您可能需要使用 Array.prototype.includes:

if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   /*** some code ***/
}

在这种情况下担心性能是过早的优化。

如果你必须使用 ES5 那么

if(~['abc', 'def', 'ghi' ,'jkl'].indexOf(x)) {...}

或更具表现力

if(!!~['abc', 'def', 'ghi' ,'jkl'].indexOf(x)) {...}