第一次我使用jQuery.inArray(),它的行为有点奇怪。

如果对象在数组中,它将返回0,但0在Javascript中是false。因此,下面将输出:"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");
}

我将不得不改变if语句为:

if(jQuery.inArray("test", myarray)==0)

但这使得代码难以阅读。特别是对于不知道这个函数的人。他们会期望jQuery。inArray("test", myarray)当"test"在数组中时返回true。

我的问题是,为什么要这样做?我真的不喜欢这个。但这样做一定有一个很好的理由。


当前回答

inArray返回数组中元素的索引,而不是指示该元素是否存在于数组中的布尔值。如果未找到该元素,则返回-1。

因此,要检查数组中是否有项,使用:

if(jQuery.inArray("test", myarray) !== -1)

其他回答

由于某些原因,当您尝试检查jquery DOM元素时,它将无法正常工作。所以重写函数就可以了:

function isObjectInArray(array,obj){
    for(var i = 0; i < array.length; i++) {
        if($(obj).is(array[i])) {
            return i;
        }
    }
    return -1;
}

而不是使用jQuery.inArray()你也可以使用包含方法int数组:

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

查看官方职位

或者,如果您想要稍微花哨一点,您可以使用按位not(~)和逻辑not(!)操作符将inArray函数的结果转换为布尔值。

if(!!~jQuery.inArray("test", myarray)) {
    console.log("is in array");
} else {
    console.log("is NOT in array");
}

inArray返回数组中元素的索引,而不是指示该元素是否存在于数组中的布尔值。如果未找到该元素,则返回-1。

因此,要检查数组中是否有项,使用:

if(jQuery.inArray("test", myarray) !== -1)

如果我们想检查一个元素是否在一组元素中,我们可以这样做:

var checkboxes_checked = $('input[type="checkbox"]:checked');

// Whenever a checkbox or input text is changed
$('input[type="checkbox"], input[type="text"]').change(function() {
    // Checking if the element was an already checked checkbox
    if($.inArray( $(this)[0], checkboxes_checked) !== -1) {
        alert('this checkbox was already checked');
    }
}