第一次我使用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,而不是它是真还是假。

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

其他回答

/^(one|two|tree)$/i.test(field) // field = Two; // true
/^(one|two|tree)$/i.test(field) // field = six; // false
/^(раз|два|три)$/ui.test(field) // field = Три; // true

这对于检查动态变量很有用。这种方法易于阅读。

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

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。

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

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

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

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

伙计,去看看医生。

例如:

var arr = [ 4, "Pete", 8, "John" ];
console.log(jQuery.inArray( "John", arr ) == 3);