简体   繁体   English

检查多个或条件的更短方式

[英]Shorter way to check multiple or conditions

Is there any easier way of checking one variables value against several others? 是否有更简单的方法来检查一个变量值与其他几个变量值? Currently I'm using code like this: 目前我正在使用这样的代码:

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

Now, is there a shorter way to do this? 现在,有更短的方法吗? I know I can use a switch , but then I'd have to write my function several times. 我知道我可以使用开关 ,但是我必须多次编写我的函数。 Is there an easier way of doing this? 有更简单的方法吗?

You do not need to write your function several times with a switch: 您无需使用开关多次编写函数:

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.
}

Amusingly, however, this is just about the same number of characters (depending on how you format it). 然而,有趣的是,这几乎是相同数量的字符(取决于你如何格式化它)。 A switch statement in general is less powerful than an explicit if statement, but in this case I find it clearer and less error-prone. 一般来说,switch语句不如显式if语句强大,但在这种情况下,我发现它更清晰,更不容易出错。

And better yet: 更好的是:

if (matchesAdjacent(a, i)) {
    // etc.
}

Move the logic out of the mainline code into an appropriately-named method. 将逻辑从主线代码移到适当命名的方法中。

This also lets you do your bounds checking there (if it isn't already guaranteed elsewhere). 这也允许你在那里进行检查(如果在其他地方没有保证)。

No. However the following looks neater: 不。但以下看起来更整洁:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM