简体   繁体   中英

jQuery inArray doesn't work when the first element matches

I'm trying to check an array that I create as to whether or not a value is in the array (anywhere) at all or not. If the value is anywhere in the array it needs to do one thing, else another.

var Arr = [false, false, false, false, false];
// It works with the following:
// Arr = [true, false, false, false, false]

if(!$.inArray(false, Arr))
{
        //False is not in the array at all - so continue with code  
}
else
{
       //False was found in the array
}

So this above code is working as if the if statement is true, however it clearly isn't.

If I change the array to: true, false, false, false, false the if statement is then false though, as it should be.

Basically what I need this code to do is to only be true if every value in the array is true .

$.inArray returns the index of the item or -1 if no items were found:

if ($.inArray(false, Arr) > -1) {
  // found
} else {
  // not found
}

Always useful to check the docs first: http://api.jquery.com/jQuery.inArray/

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).

inArray returns an integer!

So when it is at index at 0 it would be a falsely value!

You need to check > -1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM