i have this if statement and i wanna know if exist a better way to write it
if(i == "502" || i == "562" || i == "584" || i == "482" || i == "392"){
//Some Stuff here
}
i have this if statement and i wanna know if exist a better way to write it
if(i == "502" || i == "562" || i == "584" || i == "482" || i == "392"){
//Some Stuff here
}
That works fine. You can also use Array.indexOf
if(['502', '562', '584', '482', '392'].indexOf(i) !== -1)
{
/*Do Stuff*/
}
However, you should be careful with Array.indexOf
because it is not supported by versions of Internet Explorer before IE9 :(. That is why $.inArray
is often suggested over Array.indexOf
.
Use $.inArray()
method by jQuery:
var a = ['502', '562', '584', '482', '392'];
var i = '482';
if ($.inArray(i, a) > -1) {
alert(i);
}
References:
jQuery.inArray()
- jQuery API Documentationswitch(i)
{
case 502:
case 562:
case 584:
case 482:
case 392: //do stuff
break;
}
Object lookups are pretty much as fast as variable lookups.
if ({
"502": 1,
"562": 1,
"584": 1,
"482": 1, // if you're concerned about conflict with `Object.prototype`
"392": 1 // then consider using `{...}[i] === 1` or
}[i]) { // `{...}.hasOwnProperty(i)`
// code if found
}
Be aware that this method won't let you make the distinction between i === 502
and i === '502'
as all keys in Objects are Strings.
While the other answers are very useful, they don't do exactly the same as your code. If you compare a string with only digits will compare equal (using ==
) to a number it represents (and possibly other objects that have a toString()
equal to that). But the same isn't true with indexOf
, $.inArray
or switch
:
var i = 502;
i == "502"' // True
["502"].indexOf(i) // False
An exact equivalent of your code would be:
var VALUES = ['502', '562', '584', '482', '392'];
if(VALUES.some(function(e) { return e == i; }) {
// do something
}