I'm checking a variable, say foo
, for equality to a number of values. For example,
if( foo == 1 || foo == 3 || foo == 12 ) {
// ...
}
The point is that it is rather much code for such a trivial task. I came up with the following:
if( foo in {1: 1, 3: 1, 12: 1} ) {
// ...
}
but also this does not completely appeal to me, because I have to give redundant values to the items in the object.
Does anyone know a decent way of doing an equality check against multiple values?
You can write
if(foo in L(10,20,30))
if you defineL
to beUsing the answers provided, I ended up with the following:
It can be called like:
Edit: I came across this 'trick' lately which is useful if the values are strings and do not contain special characters. For special characters is becomes ugly due to escaping and is also more error-prone due to that.
To be more precise, this will check the exact string, but then again is more complicated for a simple equality test:
Also, since the values against which you're checking the result are all unique you can use the Set.prototype.has() as well.
I liked the accepted answer, but thought it would be neat to enable it to take arrays as well, so I expanded it to this:
You can remove type coercion by changing
==
to===
.For posterity you might want to use regular expressions as an alternative. Pretty good browser support as well (ref. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match#Browser_compatibility)
Try this
You could use an array and
indexOf
: