第一次我使用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。
我的问题是,为什么要这样做?我真的不喜欢这个。但这样做一定有一个很好的理由。
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>
$. 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
<code>$.inArray()</code>
vs. <code>myArray.indexOf()</code>
vs. <code>myarray.includes()</code>
when tested against
<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>