jQuery.inArray(), how to use it right?

2019-01-01 14:27发布

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.

17条回答
长期被迫恋爱
2楼-- · 2019-01-01 15:08

For some reason when you try to check for a jquery DOM element it won't work properly. So rewriting the function would do the trick:

function isObjectInArray(array,obj){
    for(var i = 0; i < array.length; i++) {
        if($(obj).is(array[i])) {
            return i;
        }
    }
    return -1;
}
查看更多
看淡一切
3楼-- · 2019-01-01 15:13

I usually use

if(!(jQuery.inArray("test", myarray) < 0))

or

if(jQuery.inArray("test", myarray) >= 0)
查看更多
浅入江南
4楼-- · 2019-01-01 15:13

instead of using jQuery.inArray() you can also use includes method for int array :

var array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

var pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

check official post here

查看更多
临风纵饮
5楼-- · 2019-01-01 15:15

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)
查看更多
怪性笑人.
6楼-- · 2019-01-01 15:15

$.inArray returns the index of the element if found or -1 if it isn't -- not a boolean value. So the correct is

if(jQuery.inArray("test", myarray) != -1) {
    console.log("is in array");
} else {
    console.log("is NOT in array");
} 
查看更多
孤独寂梦人
7楼-- · 2019-01-01 15:15

jQuery inArray() method is use to search a value in an array and return its index not a Boolean value. And if the value was not found it’ll return -1.

So, to check if a value is present in an array, follow the below practice:

myArray = new Array("php", "tutor");
if( $.inArray("php", myArray) !== -1 ) {

    alert("found");
}

Reference

查看更多
登录 后发表回答