Javascript 检查多个或多个条件的较短方法

Javascript 检查多个或多个条件的较短方法,javascript,if-statement,Javascript,If Statement,有没有更简单的方法来检查一个变量的值和其他几个变量的值?目前我使用的代码如下: if(a[i] == a[i-13] || a[i] == a[i+13] || a[i] == a[i-1] || a[i] == a[i+1]){ //my code } 现在,有没有较短的方法来实现这一点?我知道我可以使用a,但是我必须多次编写我的函数。有更简单的方法吗?没有。不过,下面看起来更整洁: if(a[i] == a[i-13] || a[i] == a[i+13] || a[i

有没有更简单的方法来检查一个变量的值和其他几个变量的值?目前我使用的代码如下:

if(a[i] == a[i-13] || a[i] == a[i+13] || a[i] == a[i-1] || a[i] == a[i+1]){
  //my code
}

现在,有没有较短的方法来实现这一点?我知道我可以使用a,但是我必须多次编写我的函数。有更简单的方法吗?

没有。不过,下面看起来更整洁:

if(a[i] == a[i-13] || 
   a[i] == a[i+13] || 
   a[i] == a[i-1] || 
   a[i] == a[i+1]
) {
  //my code
}
更好的是:

if (matchesAdjacent(a, i)) {
    // etc.
}
将逻辑从主线代码移到适当命名的方法中


这还允许您在那里进行边界检查(如果其他地方还没有保证的话)。

您不需要使用开关多次编写函数:

switch(a[i]){
  case a[i-13]:
  case a[i+13]:
  case a[i-1]:
  case a[i+1]:
    // This code will run if any of the above cases are true.
}

然而,有趣的是,这只是大约相同数量的字符(取决于格式化方式)。switch语句通常不如显式的
if
语句强大,但在这种情况下,我发现它更清晰,更不容易出错。

它可能必须是
匹配相邻(A,I)