1

I use jQuery for my application and I have an array which contains string items:

var array = ["item","item1","item2","item3"]

How I can test if array contains "item"?

Christian Groleau
8121 gold badge12 silver badges17 bronze badges
asked Feb 20, 2013 at 15:07
2

3 Answers 3

5

You can use array.indexOf("item") - It returns -1 if the item is not found or the index where the item is found.

Note that this is not supported in older versions of IE.

answered Feb 20, 2013 at 15:07
Sign up to request clarification or add additional context in comments.

3 Comments

Note that this uses === for comparison. MDN has a polyfill for those versions of IE here: developer.mozilla.org/en-US/docs/JavaScript/Reference/…
But better to use $.inArray - it will use hative Array.indexOf if available.
@dfsq - Yes, better to use $.inArray as it'll work equally well on all browsers.
4
if ($.inArray("item", array) > -1)
answered Feb 20, 2013 at 15:07

Comments

1

Javascript

Modern browsers have Array#indexOf, which does exactly that; this is in the ECMAScript v5 edition specification, but it has been in several browsers for years. Older browsers can be supported using the code listed in the "compatibility" section at the bottom of that page.

if(array.indexOf("item") > -1){
 //doSomething
}

jQuery

jQuery has a utility function for this:

if($.inArray(value, array)){
 //doSomething
}

It returns the index of a value in an array. It returns -1 if the array does not contain the value.

Duplicated?

answered Feb 20, 2013 at 15:14

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.