Is there a simpler way to rewrite the following condition in JavaScript?
if ((x == 1) || (x == 3) || (x == 4) || (x == 17) || (x == 80)) {...}
Is there a simpler way to rewrite the following condition in JavaScript?
if ((x == 1) || (x == 3) || (x == 4) || (x == 17) || (x == 80)) {...}
many options
another one, based on Ed's answer
You could use an array of valid values and test it with
indexOf
:Edit Note that
indexOf
was just added in ECMAScript 5 and thus is not implemented in every browser. But you can use the following code to add it if missing:Or, if you’re already using a JavaScript framework, you can also use its implementation of that method.
This is a little function I found somewhere on the web:
Used like this:
I'm using it for strings myself; haven't tried with numbers, but I guess it would work.
a regular expression test uses the string value of x:
You can also use the Array.includes the simplest way...