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.
jQuery.inArray() returns index of the item in the array, or -1 if item was not found. Read more here: jQuery.inArray()
The right way of using
inArray(x, arr)
is not using it at all, and using insteadarr.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.)It will return the index of the item in the array. If it's not found you will get
-1
The
inArray
function returns the index of the object supplied as the first argument to the function in the array supplied as the second argument to the function.When
inArray
returns0
it is indicating that the first argument was found at the first position of the supplied array.To use
inArray
within an if statement use:inArray
returns-1
when the first argument passed to the function is not found in the array passed as the second argument.$.inArray()
does the EXACT SAME THING asmyarray.indexOf()
and returns the index of the item you are checking the array for the existence of. It's just compatible with earlier versions of IE before IE9. The best choice is probably to usemyarray.includes()
which returns a boolean true/false value. See snippet below for output examples of all 3 methods.Man, check the doc.
for example: