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.
PHP in_array() FunctionThe in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
If you are someone strongly committed to using the jQuery library, you can use the . inArray( ) method. If the function finds the value, it returns the index position of the value and -1 if it doesn't.
inArray( value, array [, fromIndex ] )Returns: Number. Description: Search for a specified value within an array and return its index (or -1 if not found).
The jQuery inArray() method is used to find a specific value in the given array. If the value found, the method returns the index value, i.e., the position of the item. Otherwise, if the value is not present or not found, the inArray() method returns -1. This method does not affect the original array.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With