第一次我使用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。

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


当前回答

jQuery.inArray()返回数组中项目的索引,如果没有找到项目则返回-1。在这里阅读更多:jQuery.inArray()

其他回答

inArray函数返回作为第一个参数提供给函数的对象在作为第二个参数提供给函数的数组中的索引。

当inArray返回0时,表示第一个参数位于所提供数组的第一个位置。

在if语句中使用inArray:

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

当传递给函数的第一个参数在作为第二个参数传递的数组中没有找到时,inArray返回-1。

使用inArray(x, arr)的正确方法是根本不使用它,而是使用arr. indexof (x)。

官方标准名称也更清楚地说明了一个事实,即返回值是一个索引,因此如果传递的元素是第一个,则返回0(在Javascript中是假的)。

(请注意,arr.indexOf(x)直到IE9才在Internet Explorer中得到支持,所以如果你需要支持IE8或更早的版本,这将不起作用,jQuery函数是更好的选择。)

美元。inArray返回找到的元素的索引,如果没有返回-1——不是布尔值。正确的是

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

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

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');
    }
}

inArray返回数组中元素的索引。如果没有找到该元素,则返回-1 else index of element。

if(jQuery.inArray("element", myarray) === -1) {
    console.log("Not exists in array");
} else {
    console.log("Exists in array");
}