pimvdb pimvdb - 6 months ago 39
Javascript Question

Check variable equality against a list of values

I'm checking a variable, say

, 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?


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.


To be more precise, this will check the exact string, but then again is more complicated for a simple equality test: