-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';
2
  • array('test','about','try'); ? Should it be new Array(...) or [....] ? Commented Apr 19, 2016 at 8:11
  • It's well worth your time reading through the jQuery API beginning to end. It takes about an hour, two tops. Commented Apr 19, 2016 at 8:12

3 Answers 3

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

it should be >= because item can be in 0 position in array.
@jcubic: thanks. missed = operator there
1

You can use indexOf() method like following.

if(sites.indexOf(element) > -1) {
    //exist
}

1 Comment

If IE8 support matters, that would need a polyfill or just use jQuery $.inArray() method
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.