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

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


当前回答

它将返回数组中该项的索引。如果没有找到,就会得到-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');
    }
}

而不是使用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

查看官方职位

答案来自文档的第一段,检查结果是否大于-1,而不是它是真还是假。

$. inarray()方法类似于JavaScript的原生. indexof()方法,当它没有找到匹配时返回-1。如果数组中的第一个元素与value匹配,$. inarray()返回0。 因为JavaScript将0视为松散等于false(即0 == false,但0 !== false),如果我们要检查数组中是否存在value,我们需要检查它是否不等于(或大于)-1。

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

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

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

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。