3

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
}
  • 1
    The answers you're getting are performing a strict equality comparison. Since you're doing a `==` comparison, this could change the result. For example, if `i` is `502` instead of `"502"`, yours will be `true`, while the others will be `false`. –  Jun 01 '13 at 15:20
  • Then try `/^(?:502|562|584|482|392)$/.test(i)`, which will do string coercion as well :-) – Bergi Jun 01 '13 at 15:41

5 Answers5

5

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.

Steven Wexler
  • 16,589
  • 8
  • 53
  • 80
  • on some older browsers (IE, im watching at you...) there is no method indexOf() for prototype array, you should then use jquery method: $.inArray() but it's quite a nice approach imo – A. Wolff Jun 01 '13 at 15:13
  • Thanks for calling this out. I'm in the process of modifying my post now to call out browser compatibility issues. – Steven Wexler Jun 01 '13 at 15:14
  • @roasted: On the page he linked there's a *Compatibility* section to read (including a simple solution) - no reason to repeat this over and over :-) – Bergi Jun 01 '13 at 15:20
  • @Bergi have you see the little link where it is marked 'edited' ;) – A. Wolff Jun 01 '13 at 15:21
3

Use $.inArray() method by jQuery:

var a = ['502', '562', '584', '482', '392'];
var i = '482';

if ($.inArray(i, a) > -1) {
    alert(i);
}

References:

  • Note that this is great if compatibility is a major concern. If you don't have to deal with old IE, then the native implementation steaks suggests is faster. – lonesomeday Jun 01 '13 at 15:09
3
switch(i)
{
   case 502:
   case 562:
   case 584:
   case 482:
   case 392: //do stuff
            break;
}
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1

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.

Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • 1
    Though it's unlikely, you can get false positives if `i` happens to be a string with the same name as a method on `Object.prototype`. Again, pretty unlikely, but I think it's worth noting. Using `.hasOwnProperty()` would be safer. –  Jun 01 '13 at 15:28
  • @CrazyTrain that is true, `constructor`, `hasOwnProperty`, `propertyIsEnumerable`, `toLocaleString`, `toString` and `valueOf`, as well as `__define` and `__lookup` for _Getter_ and _Setter_ are the possible conflicts. If you know you're looking up a string like in the example you don't have to worry, and if you want to keep the fast lookup you could do an `===` test against what you set the value to (i.e. here would be `{...}[i] === 1`) – Paul S. Jun 01 '13 at 15:34
  • +1 for the updates! :-) –  Jun 01 '13 at 15:58
  • Another option is to cast with `+` as `+undefined` and `+function () {}` are both `NaN` (_falsy_). – Paul S. Jun 01 '13 at 16:18
  • Creative solution! Seems like that would totally work. Only possibilities then would be extreme edge cases, like extensions to `Object.prototype` with truthy numeric values, or even less likely, something like `Function.prototype.toString = function() { return 1; }` ...Yes, completely silly, and not worth worrying about, but *technically* possible. :-) –  Jun 01 '13 at 16:33
  • 1
    D: If someone adds something to `Object.prototype` like that except as a joke, they should be banned from eating chocolate and cookies for the rest of their life. _JavaScript_ gives you prototyping and constructors for that stuff. – Paul S. Jun 01 '13 at 16:37
  • 1
    Completely agree! Hence the *"extreme edge cases"*, assuming most people like chocolate, and don't like buggy JavaScript. ;) –  Jun 01 '13 at 16:40
1

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
}
lqc
  • 7,434
  • 1
  • 25
  • 25
  • +1 This is the only truly accurate alternative, though it doesn't shorten it since I'm guessing that's what is ultimately wanted. But if this is done in several places, you could make the function named, and just do `VALUES.some(compare)`, which would be nice. –  Jun 01 '13 at 15:31
  • ...oops, my function above would need to be `VALUES.some(compare(i))` with `compare` returning a function. And maybe an improved function name would be `compareTo`... `VALUES.some(compareTo(i))` –  Jun 01 '13 at 15:51