Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  158] [ 3]  / answers: 1 / hits: 191444  / 14 Years ago, tue, january 18, 2011, 12:00:00

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?


More From » javascript

 Answers
22

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);

[#94161] Monday, January 17, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aidengiancarlop

Total Points: 234
Total Questions: 115
Total Answers: 94

Location: India
Member since Wed, Aug 26, 2020
4 Years ago
;