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"?
-
developer.mozilla.org/en-US/docs/JavaScript/Reference/…Jack– Jack2013年02月20日 15:07:55 +00:00Commented Feb 20, 2013 at 15:07
-
Now I think is duplicated :(Tomas Ramirez Sarduy– Tomas Ramirez Sarduy2013年02月20日 15:19:28 +00:00Commented Feb 20, 2013 at 15:19
3 Answers 3
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.
3 Comments
===
for comparison. MDN has a polyfill for those versions of IE here: developer.mozilla.org/en-US/docs/JavaScript/Reference/… $.inArray
- it will use hative Array.indexOf
if available.$.inArray
as it'll work equally well on all browsers.if ($.inArray("item", array) > -1)
Comments
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.