jQuery.inArray(), how to use it right?

2019-01-01 14:27发布

First time I work with jQuery.inArray() and it acts kinda strange.

If the object is in the array, it will return 0, but 0 is false in Javascript. So the following will output: "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");
}

I will have to change the if statement to:

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

But this makes the code unreadable. Especially for someone who doesn't know this function. They will expect that jQuery.inArray("test", myarray) gives true when "test" is in the array.

So my question is, why is it done this way? I realy dislike this. But there must be a good reason to do it like that.

17条回答
孤独总比滥情好
2楼-- · 2019-01-01 14:56

jQuery.inArray() returns index of the item in the array, or -1 if item was not found. Read more here: jQuery.inArray()

查看更多
有味是清欢
3楼-- · 2019-01-01 14:57

The right way of using inArray(x, arr) is not using it at all, and using instead arr.indexOf(x).

The official standard name is also more clear on the fact that the returned value is an index thus if the element passed is the first one you will get back a 0 (that is falsy in Javascript).

(Note that arr.indexOf(x) is not supported in Internet Explorer until IE9, so if you need to support IE8 and earlier, this will not work, and the jQuery function is a better alternative.)

查看更多
人间绝色
4楼-- · 2019-01-01 14:58

It will return the index of the item in the array. If it's not found you will get -1

查看更多
倾城一夜雪
5楼-- · 2019-01-01 15:03

The inArray function returns the index of the object supplied as the first argument to the function in the array supplied as the second argument to the function.

When inArray returns 0 it is indicating that the first argument was found at the first position of the supplied array.

To use inArray within an if statement use:

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

inArray returns -1 when the first argument passed to the function is not found in the array passed as the second argument.

查看更多
听够珍惜
6楼-- · 2019-01-01 15:05

$.inArray() does the EXACT SAME THING as myarray.indexOf() and returns the index of the item you are checking the array for the existence of. It's just compatible with earlier versions of IE before IE9. The best choice is probably to use myarray.includes() which returns a boolean true/false value. See snippet below for output examples of all 3 methods.

// 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>

查看更多
浮光初槿花落
7楼-- · 2019-01-01 15:05

Man, check the doc.

for example:

var arr = [ 4, "Pete", 8, "John" ];
console.log(jQuery.inArray( "John", arr ) == 3);
查看更多
登录 后发表回答