-2

How can I check if the var element exists or not in the array sites?

var sites = array['test','about','try'];
var element = 'other';
Daniel
  • 63
  • 4
  • `array('test','about','try');` ? Should it be `new Array(...)` or `[....]` ? – Rayon Apr 19 '16 at 08:11
  • It's ***well worth*** your time reading through [the jQuery API](http://api.jquery.com) beginning to end. It takes about an hour, two tops. – T.J. Crowder Apr 19 '16 at 08:12

3 Answers3

2

You can use inArray:

Search for a specified value within an array and return its index (or -1 if not found).

var sites = ['test','about','try'];
var element = 'other';
if($.inArray(element ,sites ) >= 0){
  //exists
}
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

You can use indexOf() method like following.

if(sites.indexOf(element) > -1) {
    //exist
}
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
0
if (jQuery.inArray(jQuery("input:first").val(), ar) != -1)

The inArray method returns -1 if the element wasn't found in the array, so as your bonus answer to how to determine if an element is not in an array, use this :

if(jQuery.inArray(el,arr) == -1){
    // the element is not in the array
};

Source :JS jQuery - check if value is in array

Community
  • 1
  • 1
REDEVI_
  • 684
  • 8
  • 18