最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Shorter way to check multiple or conditions - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Oct 28, 2011 at 15:07 Some GuySome Guy 16.2k10 gold badges60 silver badges68 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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.

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
}
发布评论

评论列表(0)

  1. 暂无评论