First time I work with jQuery.inArray()
and it acts kinda strange.
If the object is in the array, it will return 0, but 0 is false in Javascript. So the following will output: "is NOT in array"
var myarray = [];
myarray.push("test");
if(jQuery.inArray("test", myarray)) {
console.log("is in array");
} else {
console.log("is NOT in array");
}
I will have to change the if statement to:
if(jQuery.inArray("test", myarray)==0)
But this makes the code unreadable. Especially for someone who doesn't know this function. They will expect that jQuery.inArray("test", myarray) gives true when "test" is in the array.
So my question is, why is it done this way? I realy dislike this. But there must be a good reason to do it like that.
For some reason when you try to check for a jquery DOM element it won't work properly. So rewriting the function would do the trick:
I usually use
or
instead of using
jQuery.inArray()
you can also useincludes
method for int array :check official post here
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:
$.inArray
returns the index of the element if found or -1 if it isn't -- not a boolean value. So the correct isjQuery 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:
Reference