Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 511
nbar Avatar asked Sep 18 '13 08:09

nbar


People also ask

How do you use inArray?

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.

How do you check if an array contains a specific value in jQuery?

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.

How do you find if an array contains a specific string in jQuery?

inArray( value, array [, fromIndex ] )Returns: Number. Description: Search for a specified value within an array and return its index (or -1 if not found).

What is inArray?

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.


1 Answers

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) 
like image 178
Dennis Avatar answered Sep 30 '22 03:09

Dennis