jQuery.inArray () วิธีการใช้งานถูกต้อง?


345

ครั้งแรกที่ฉันทำงานด้วยjQuery.inArray()และมันก็ทำหน้าที่แปลก ๆ

หากวัตถุอยู่ในอาร์เรย์วัตถุจะคืนค่า 0 แต่ 0 จะเป็นเท็จใน Javascript ดังนั้นผลลัพธ์ต่อไปนี้: "ไม่ได้อยู่ในอาร์เรย์"

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" อยู่ในอาร์เรย์

ดังนั้นคำถามของฉันคือทำไมมันทำแบบนี้? ฉันไม่ชอบสิ่งนี้จริงๆ แต่ต้องมีเหตุผลที่ดีที่จะทำเช่นนั้น

คำตอบ:


734

inArrayส่งคืนดัชนีขององค์ประกอบในอาร์เรย์ไม่ใช่บูลีนที่ระบุว่ามีรายการอยู่ในอาร์เรย์หรือไม่ หากไม่พบองค์ประกอบ-1จะถูกส่งคืน

ดังนั้นในการตรวจสอบว่ารายการนั้นอยู่ในอาร์เรย์หรือไม่ให้ใช้:

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

16
CoffeeScript:if jQuery.inArray('test', myarray) isn't -1
Joshua Pinter

9
แน่นอนคุณสามารถกำหนดฟังก์ชั่นการใช้งานของคุณเองได้ง่ายขึ้น$.isInArray = function(test,array) { return $.inArray(test, array) !== -1; };
Wesley Smith

1
หรือสั้น: $.isInArray = function(item, array) { return !!~$.inArray(item, array); };(ฉันจะเก็บรหัสลับที่ต้องการในฟังก์ชั่นการตั้งชื่อที่ดีที่จะทำให้ความตั้งใจที่ชัดเจนแม้ว่า :))
เดนนิส

2
ขอบคุณ @ Chips_100 ที่แสดงให้เราเห็นผู้เรียนรู้วิธีการทำอย่างถูกต้องมันคงจะดีถ้า jQuery สามารถอัปเดตเพื่อรวมไว้ในตัวอย่างของพวกเขาเอง
asherrard

2
คุณสามารถใช้if( $.inArray(test, array) > -1) { // do stuff }
MistyDawn

48

$.inArrayส่งคืนดัชนีขององค์ประกอบหากพบหรือ -1 ถ้าไม่ใช่ - ไม่ใช่ค่าบูลีน ดังนั้นสิ่งที่ถูกต้องคือ

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

26

คำตอบมาจากย่อหน้าแรกของการตรวจสอบเอกสารว่าผลลัพธ์มากกว่า -1 ไม่ใช่เป็นจริงหรือเท็จ

วิธี $ .inArray () คล้ายกับเมธอด. indexOf () ดั้งเดิมของ JavaScript ซึ่งจะส่งคืน -1 เมื่อไม่พบข้อมูลที่ตรงกัน ถ้าองค์ประกอบแรกภายในอาร์เรย์จับคู่กับค่า $ .inArray () จะคืนค่า 0

เนื่องจากจาวาสคริปต์นั้นถือว่า 0 เท่ากับคับเท่ากับเท็จ (เช่น 0 == false แต่ 0! == false) หากเรากำลังตรวจสอบว่ามีค่าอยู่ในอาร์เรย์หรือไม่เราต้องตรวจสอบว่ามันไม่เท่ากับ (หรือมากกว่า ) -1


23

วิธีการที่เหมาะสมของการใช้inArray(x, arr)จะไม่ได้ใช้มันเลยarr.indexOf(x)และใช้แทน

ชื่อมาตรฐานอย่างเป็นทางการนั้นมีความชัดเจนมากขึ้นเกี่ยวกับความจริงที่ว่าค่าที่ส่งคืนเป็นดัชนีดังนั้นหากองค์ประกอบที่ส่งผ่านเป็นชื่อแรกคุณจะได้รับกลับคืน0(นั่นคือเท็จใน Javascript)

(หมายเหตุว่าarr.indexOf(x)จะได้รับการสนับสนุนใน Internet Explorer จนกว่า IE9ดังนั้นหากคุณต้องการที่จะสนับสนุน IE8 และก่อนหน้านี้จะไม่ทำงานและฟังก์ชั่น jQuery เป็นทางเลือกที่ดีกว่า.)


1
ฉันต้องยอมรับ ชื่อของ inArray สับสน ดูเหมือนว่ามันควรจะส่งคืนบูลีน แต่ก็ทำเช่นเดียวกันกับ indexOf
Enrique Moreno Tent

ทุกครั้งที่ฉัน$.inArrayใช้จุดเริ่มต้นของรหัสฉันต้องไปแก้ไขข้อบกพร่องฉันคร่ำครวญ อย่างไรก็ตามนี่เป็นคำตอบที่ได้รับการยอมรับ
Aluan Haddad

11

หรือถ้าคุณอยากได้แฟนซีคุณสามารถใช้ตัวดำเนินการ bitwise not (~) และ logical not (!) เพื่อแปลงผลลัพธ์ของฟังก์ชัน inArray เป็นค่าบูลีน

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

4
การใช้ตัวดำเนินการ bitwise โดยทั่วไปจะถูกห้าม / frowned ตามมาตรฐานการเข้ารหัส JavaScript ทั่วไป ดังนั้นหากคุณใช้โอกาสในการใช้ linter (jshint, eslint เป็นต้น) คุณจะไม่ได้รับการตรวจสอบโค้ด วิธีแก้ปัญหาทำงานแม้ว่า
jhrr

8

ฉันมักจะใช้

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

หรือ

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

3
ดียิ่งขึ้น ...if( $.inArray("test", myarray) > -1 )
MistyDawn

8

jQuery inArray () วิธีการใช้ในการค้นหาค่าในอาร์เรย์และกลับดัชนีของมันไม่ใช่ค่าบูลีน และถ้าไม่พบค่ามันจะคืนค่า -1

ดังนั้นหากต้องการตรวจสอบว่ามีค่าอยู่ในอาร์เรย์หรือไม่ให้ทำตามวิธีปฏิบัติด้านล่าง:

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

    alert("found");
}

การอ้างอิง


7

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เมื่อไม่พบอาร์กิวเมนต์แรกที่ส่งไปยังฟังก์ชันในอาร์เรย์ที่ส่งผ่านเป็นอาร์กิวเมนต์ที่สอง


5

แทนที่จะใช้jQuery.inArray()คุณยังสามารถใช้includesวิธีการสำหรับ int 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

ตรวจสอบโพสต์อย่างเป็นทางการที่นี่


1
ไม่รองรับ IE - :: use indeOf
anoldermark

3

jQuery.inArray () ส่งคืนดัชนีของรายการในอาร์เรย์หรือ -1 หากไม่พบรายการ อ่านเพิ่มเติมได้ที่นี่: jQuery.inArray ()



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');
    }
}

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

สิ่งนี้มีประโยชน์สำหรับการตรวจสอบตัวแปรแบบไดนามิก วิธีนี้อ่านง่าย


2

$.inArray()ไม่สิ่งเดียวที่แน่นอนเป็นmyarray.indexOf()และผลตอบแทนดัชนีของรายการที่คุณกำลังตรวจสอบอาร์เรย์สำหรับการดำรงอยู่ของ มันเข้ากันได้กับ IE รุ่นก่อนหน้านี้ก่อน IE9 ตัวเลือกที่ดีที่สุดน่าจะใช้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>


ควรสังเกตว่า$.inArrayควรเป็นมาตรฐานทองคำหากคุณมีสิทธิ์เข้าถึงไลบรารี jQuery มิฉะนั้นควรใช้ JavaScript ที่.indexOfมี polyfill สำหรับ IE8 แทน อยู่ห่างจากสิ่งที่ทันสมัยเช่น.includes()นั้น
Alexander Dixon


1

ด้วยเหตุผลบางอย่างเมื่อคุณพยายามตรวจสอบองค์ประกอบ DOM ของ jquery มันจะทำงานไม่ถูกต้อง ดังนั้นการเขียนใหม่ฟังก์ชั่นจะทำเคล็ดลับ:

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

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>


0

ไม่มีใครใช้$แทนjQuery:

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

ฉันแค่อยากรู้ว่าทำไม มีปัญหาความเข้ากันได้ผิดปกติสาเหตุนี้หรือไม่ ฉันไม่เคยมีชนิดของปัญหาใด ๆ ใช้แทน$ jQuery
MistyDawn

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.