jQuery.inArray(), how to use it right?
Solution 1:
inArray
returns the index of the element in the array, not a boolean indicating if the item exists in the array. If the element was not found, -1
will be returned.
So, to check if an item is in the array, use:
if(jQuery.inArray("test", myarray) !== -1)
Solution 2:
$.inArray
returns the index of the element if found or -1 if it isn't -- not a boolean value. So the correct is
if(jQuery.inArray("test", myarray) != -1) {
console.log("is in array");
} else {
console.log("is NOT in array");
}
Solution 3:
The answer comes from the first paragraph of the documentation check if the results is greater than -1, not if it's true or false.
The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.
Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1.
Solution 4:
The right way of using inArray(x, arr)
is not using it at all, and using instead arr.indexOf(x)
.
The official standard name is also more clear on the fact that the returned value is an index thus if the element passed is the first one you will get back a 0
(that is falsy in Javascript).
(Note that arr.indexOf(x)
is not supported in Internet Explorer until IE9, so if you need to support IE8 and earlier, this will not work, and the jQuery function is a better alternative.)
Solution 5:
jQuery inArray() method is use to search a value in an array and return its index not a Boolean value. And if the value was not found it’ll return -1.
So, to check if a value is present in an array, follow the below practice:
myArray = new Array("php", "tutor");
if( $.inArray("php", myArray) !== -1 ) {
alert("found");
}
Reference