第一次我使用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函数返回作为第一个参数提供给函数的对象在作为第二个参数提供给函数的数组中的索引。

当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返回找到的元素的索引,如果没有返回-1——不是布尔值。正确的是

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

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


它将返回数组中该项的索引。如果没有找到,就会得到-1


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

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


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

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

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

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

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

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

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

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


只是没有人使用$而不是jQuery:

if ($.inArray(nearest.node.name, array)>=0){
   console.log("is in array");
}else{
   console.log("is not in array");
}

我通常用

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

or

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

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

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()方法用于搜索数组中的值,并返回其索引而不是布尔值。如果没有找到值,它将返回-1。

因此,要检查一个值是否存在于数组中,请遵循以下实践:

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

    alert("found");
}

参考


伙计,去看看医生。

例如:

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

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

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


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

查看官方职位


$. inarray()与myarray.indexOf()做完全相同的事情,并返回你正在检查数组中是否存在的项的索引。它只与IE9之前的IE版本兼容。最好的选择可能是使用myarray.includes(),它返回一个布尔值true/false。有关所有3种方法的输出示例,请参见下面的代码片段。

// Declare the array and define it's values var myarray = ['Cat', 'Dog', 'Fish']; // Display the return value of each jQuery function // when a radio button is selected $('input:radio').change( function() { // Get the value of the selected radio var selectedItem = $('input:radio[name=arrayItems]:checked').val(); $('.item').text( selectedItem ); // Calculate and display the index of the selected item $('#indexVal').text( myarray.indexOf(selectedItem) ); // Calculate and display the $.inArray() value for the selected item $('#inArrVal').text( $.inArray(selectedItem, myarray) ); // Calculate and display the .includes value for the selected item $('#includeVal').text( myarray.includes(selectedItem) ); }); #results { line-height: 1.8em; } #resultLabels { width: 14em; display: inline-block; margin-left: 10px; float: left; } label { margin-right: 1.5em; } .space { margin-right: 1.5em; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Click a radio button to display the output of &nbsp;<code>$.inArray()</code> &nbsp;vs. <code>myArray.indexOf()</code> &nbsp;vs. <code>myarray.includes()</code> &nbsp;when tested against &nbsp;<code>myarray = ['Cat', 'Dog', 'Fish'];</code><br><br> <label><input type="radio" name="arrayItems" value="Cat"> Cat</label> <label><input type="radio" name="arrayItems" value="Dog"> Dog</label> <label><input type="radio" name="arrayItems" value="Fish"> Fish</label> <label><input type="radio" name="arrayItems" value="N/A"> ← Not in Array</label> <br><br> <div id="results"> <strong>Results:</strong><br> <div id="resultLabels"> myarray.indexOf( "<span class="item">item</span>" )<br> $.inArray( "<span class="item">item</span>", myarray )<br> myarray.includes( "<span class="item">item</span>" ) </div> <div id="resultOutputs"> <span class="space">=</span><span id="indexVal"></span><br> <span class="space">=</span><span id="inArrVal"></span><br> <span class="space">=</span><span id="includeVal"></span> </div> </div>


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

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

var abc = { "partner": { "name": "North East & Cumbria (EDT)", "number": "01915008717", "areas": { "authority": ["Allerdale", "Barrow-in-Furness", "Carlisle"] } } }; $.each(abc.partner.areas, function(key, val){ console.log(val); if(jQuery.inArray("Carlisle", val)) { console.log(abc.partner.number); } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


最短最简单的方法是。

arrayHere = ['cat1', 'dog2', 'bat3']; 

if(arrayHere[any key want to search])   
   console.log("yes found in array");

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

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