user188962
user188962

Reputation:

Check if Variable in array javascript

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

Upvotes: 2

Views: 1254

Answers (3)

Svante Svenson
Svante Svenson

Reputation: 12478

if(some_array[category] !== undefined){
  // it's there
}

Upvotes: 0

Select0r
Select0r

Reputation: 12658

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

Upvotes: 0

kennytm
kennytm

Reputation: 523534

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

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

Upvotes: 1

Related Questions