最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery inArray doesn't work when the first element matches - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Feb 22, 2013 at 1:01 user166390 asked Feb 22, 2013 at 0:49 Dylan CrossDylan Cross 5,98623 gold badges79 silver badges120 bronze badges 1
  • 3 It's a poorly named method. They should have called it indexOf() like the standard method Arr.indexOf(false) === -1. – the system Commented Feb 22, 2013 at 0:58
Add a ment  | 

2 Answers 2

Reset to default 14

$.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./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

发布评论

评论列表(0)

  1. 暂无评论