1

Possible Duplicate:
javascript function inArray

In Python, I can do multi-equivalence testing by doing:

if x in [1, 2, 3, 4, 5]:
    do something

How would I do this in javascript?. Currently I'm doing:

if (x == 1 || x == 2 || x == 3 || x == 4 || x == 5) {
    do something
}
Community
  • 1
  • 1
David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

6

In JavaScript there is indexOf method:

if ([1,2,3,4,5].indexOf(x) > -1) {
    // do something
}

Note, that this method is not supported by some old browsers, so it is recommended to use shim.

By the way, in operator exists in JavaScript, and is primarily used for checking property existence in objects, for example:

"id" in { id: 123 } === true;
"id" in { ib: 123 } === false;
VisioN
  • 143,310
  • 32
  • 282
  • 281
0

You can use a switch if you only want to specify the x variable once:

switch (x) {
  case 1:
  case 2:
  case 3:
  case 4:
  case 5:
    // do something
}

If the values are really like in the example, you can just check the end values:

if (x >= 1 && x <= 5) {
  // do something
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005