2

Short code for checking if a variable also exists inside an array is needed. Im thinking something like this:

   var category='cars';
   if (in_array(category, some_array)){
       do stuff!
   }

Is there any such function in js?

Thanks

3 Answers3

1
if (some_array.indexOf(category) >= 0) {
   // do stuff
}

(Ref: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf)

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • Not native in IE, but the link you posted does show an example implementation using `Array.prototype`. – Andy E Feb 19 '10 at 15:17
0

There's no native "in_array"-function in JavaScript (as in PHP), check out this solution:

http://phpjs.org/functions/in_array:432

Also a search would have lead you here:

JavaScript equivalent of PHP's in_array()

Community
  • 1
  • 1
Select0r
  • 12,234
  • 11
  • 45
  • 68
0
if(some_array[category] !== undefined){
  // it's there
}
Svante Svenson
  • 12,315
  • 4
  • 41
  • 45