jQuery.inArray(), how to use it right?

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.

20 Answers
20

Leave a Comment