Check variable equality against a list of values
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 could use an array and indexOf
:
if ([1,3,12].indexOf(foo) > -1)
In ECMA2016 you can use the includes method. It's the cleanest way I've seen. (Supported by all major browsers)
if([1,3,12].includes(foo)) {
// ...
}
Using the answers provided, I ended up with the following:
Object.prototype.in = function() {
for(var i=0; i<arguments.length; i++)
if(arguments[i] == this) return true;
return false;
}
It can be called like:
if(foo.in(1, 3, 12)) {
// ...
}
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.
/foo|bar|something/.test(str);
To be more precise, this will check the exact string, but then again is more complicated for a simple equality test:
/^(foo|bar|something)$/.test(str);