Is there a better way to write the following conditional in javascript?
if ( value == 1 || value == 16 || value == -500 || value == 42.42 || value == \'somet
You could extend the array object:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
Then if you store all those values in an array you could do something like MyValues.contains(value)
var value= -55;
switch(value){
case 1: case 16: case -55: case 42.5: case 'something':
alert(value); break;
}
switch is an acceptable choice. You can also use a map, depending on the complexity of the problem (assuming you have more than you put in your example).
var accept = { 1: true, 16: true, '-500': true, 42.42: true, something: true };
if (accept[value]) {
// blah blah blah
}
accept could be generated progamatically from an array of course. Depends really on how much you plan on using this pattern. :/
Well, you could use a switch statement...
switch (value) {
case 1 : // blah
break;
case 16 : // blah
break;
case -500 : // blah
break;
case 42.42: // blah
break;
case "something" : // blah
break;
}
If you're using JavaScript 1.6 or greater, you can use the indexOf notation on an array:
if ([1, 16, -500, 42.42, "something"].indexOf(value) !== -1) {
// blah
}
And for the ultimate in hackiness, you can coerce the values to strings (this works for all browsers):
if ("1,16,-500,42.42,something".indexOf(value) !== -1) {
// blah
}
In an effort to make yet another way of doing it...
if (/^(1|16|-500|42.42|something)$/.test(value)) {
// blah blah blah
}
No need to extend array prototypes or anything, just use a quick regexp to test the value!
var a = [1, 16, -500, 42.42, 'something'];
var value = 42;
if (a.indexOf(value) > -1){
// blah blah blah
}
Upd: Utility function sample as proposed in comments:
Object.prototype.in = function(){
for(var i = 0; i < arguments.length; i++){
if (this == arguments[i]) return true;
}
return false;
}
So you can write:
if (value.in(1, 16, -500, 42.42, 'something')){
// blah blah blah
}