Test for value in Javascript Array [duplicate]

In SQL Server, I could say:

WHERE X IN(1,2)

How would you rewrite the following in JavaScript:

if (X==1 || X==2) {}

Use indexOf to see if x is in an array.

if([1,2].indexOf(x) !== -1)

Using Array .includes method.

if ([1, 2].includes(x)) {
  // array has x
}

Try using an array, and then its .indexOf().

 var myNumbers = [1,2];
 var foo = 4;
 var bar = 1;

 var exists = (myNumbers.indexOf(bar) > -1); //true
 var notExists = (myNumbers.indexOf(foo) > -1); //false

There's no silver bullet. There will be a few gotchas.

If you do indexOf as some answers suggest, you need to remember that Array.indexOf is not supported in all browsers, so you need to provide your own fallback. Also this will have a performance of O(n) since it needs to traverse the whole array, which might not be ideal if you're dealing with a huge array.

If you use the in operator as other answers suggest, you need to remember that in Javascript object's properties are always strings, so don't expect === checks to work if you're checking for numbers.

In this particular example you suggested, I would just go for the good old if (X==1 || X==2).


if (x in {1:true, 2:true}) { }

Or, if you want to abstract it you could do it like this http://snook.ca/archives/javascript/testing_for_a_v

function oc(a) { var o = {}; for(var i=0;i

Still... not the most scalable thing to be doing