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.
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.
This is useful for checking dynamic variables. This method is easy to read.
Just no one use
$
instead ofjQuery
:If we want to check an element is inside a set of elements we can do for example:
Or if you want to get a bit fancy you can use the bitwise not (~) and logical not(!) operators to convert the result of the inArray function to a boolean value.