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"?
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"?
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.
if ($.inArray("item", array) > -1)
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 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.