383

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

如果对象在数组中,它将返回 0,但 0 在 Javascript 中为 false。所以以下将输出:“不在数组中”

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。

所以我的问题是,为什么要这样做?我真的不喜欢这个。但必须有充分的理由这样做。

4

20 回答 20

821

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

因此,要检查一个项目是否在数组中,请使用:

if(jQuery.inArray("test", myarray) !== -1)
于 2013-09-18T08:47:03.547 回答
56

$.inArray如果找到则返回元素的索引,否则返回 -1 - 不是布尔值。所以正确的是

if(jQuery.inArray("test", myarray) != -1) {
    console.log("is in array");
} else {
    console.log("is NOT in array");
} 
于 2013-09-18T08:46:27.383 回答
26

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

$.inArray() 方法类似于 JavaScript 的原生 .indexOf() 方法,因为它在找不到匹配项时返回 -1。如果数组中的第一个元素与值匹配,则 $.inArray() 返回 0。

因为 JavaScript 将 0 视为松散地等于 false(即 0 == false,但 0 !== false),如果我们要检查数组中是否存在值,我们需要检查它是否不等于(或大于) -1。

于 2013-09-18T08:46:41.557 回答
25

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

官方标准名称也更清楚地表明返回值是一个索引,因此如果传递的元素是第一个元素,您将返回 a 0(在 Javascript 中是虚假的)。

(请注意,IE9 之前的 Internet Explorer 不支持arr.indexOf(x),所以如果您需要支持 IE8 及更早版本,这将不起作用,而 jQuery 函数是更好的选择。)

于 2015-01-08T09:08:53.530 回答
13

jQuery inArray() 方法用于搜索数组中的值并返回其索引而不是布尔值。如果找不到该值,它将返回-1。

因此,要检查数组中是否存在值,请遵循以下做法:

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

    alert("found");
}

参考

于 2016-10-22T11:53:52.813 回答
12

或者,如果您想花点心思,可以使用按位非 (~) 和逻辑非 (!) 运算符将 inArray 函数的结果转换为布尔值。

if(!!~jQuery.inArray("test", myarray)) {
    console.log("is in array");
} else {
    console.log("is NOT in array");
}
于 2014-07-17T02:45:30.570 回答
11

除了使用jQuery.inArray()你还可以使用includesint array 的方法:

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

在这里查看官方帖子

于 2018-01-10T11:41:45.317 回答
10

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

inArray返回时0表示在提供的数组的第一个位置找到第一个参数。

inArray在 if 语句中使用,请使用:

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

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

于 2013-09-18T08:46:16.997 回答
8

我通常使用

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

或者

if(jQuery.inArray("test", myarray) >= 0)
于 2016-04-20T09:38:18.907 回答
4

inArray返回数组中元素的索引。如果未找到元素,则返回-1,否则返回元素索引。

if(jQuery.inArray("element", myarray) === -1) {
    console.log("Not exists in array");
} else {
    console.log("Exists in array");
}
于 2020-09-25T13:44:44.703 回答
3

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

于 2013-09-18T08:46:29.390 回答
3

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

于 2013-09-18T08:46:37.213 回答
3

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

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');
    }
}
于 2016-06-20T16:38:28.317 回答
3

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>

于 2019-01-14T15:49:30.387 回答
2
/^(one|two|tree)$/i.test(field) // field = Two; // true
/^(one|two|tree)$/i.test(field) // field = six; // false
/^(раз|два|три)$/ui.test(field) // field = Три; // true

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

于 2017-03-08T13:48:10.910 回答
2

$.inArray()执行完全相同的操作myarray.indexOf()并返回您正在检查数组是否存在的项目的索引。它只是与 IE9 之前的早期版本的 IE 兼容。最好的选择可能是使用myarray.includes()它返回一个布尔真/假值。有关所有 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>

于 2018-07-06T22:35:00.060 回答
1

伙计,检查文档

例如:

var arr = [ 4, "Pete", 8, "John" ];
console.log(jQuery.inArray( "John", arr ) == 3);
于 2017-02-07T16:06:40.263 回答
1

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

function isObjectInArray(array,obj){
    for(var i = 0; i < array.length; i++) {
        if($(obj).is(array[i])) {
            return i;
        }
    }
    return -1;
}
于 2018-11-27T10:16:17.517 回答
0

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

if ($.inArray(nearest.node.name, array)>=0){
   console.log("is in array");
}else{
   console.log("is not in array");
}
于 2015-10-06T05:15:53.237 回答
-5

最短和最简单的方法是。

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

if(arrayHere[any key want to search])   
   console.log("yes found in array");
于 2020-06-18T15:54:41.043 回答