อาร์เรย์ JavaScript findIndex()
ตัวอย่าง 1
ค้นหาองค์ประกอบแรกที่มีค่ามากกว่า 18:
const ages = [3, 10, 18, 20];
ages.findIndex(checkAge);
function checkAge(age) {
return age > 18;
}
ความหมายและการใช้งาน
findIndex()
เมธอดเรียกใช้ฟังก์ชันสำหรับแต่ละองค์ประกอบอาร์เรย์
วิธี การfindIndex()
ส่งคืนดัชนี (ตำแหน่ง) ขององค์ประกอบแรกที่ผ่านการทดสอบ
เมธอดจะคืน ค่าfindIndex()
-1 หากไม่พบรายการที่ตรงกัน
เมธอด นี้findIndex()
ไม่เรียกใช้ฟังก์ชันสำหรับอิลิเมนต์อาร์เรย์ว่าง
วิธี การfindIndex()
นี้จะไม่เปลี่ยนอาร์เรย์เดิม
ไวยากรณ์
array.findIndex(function(currentValue, index, arr), thisValue)
พารามิเตอร์
Parameter | Description |
function() | Required. A function to be run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default undefined .A value passed to the function as its this value. |
คืนมูลค่า
พิมพ์ | คำอธิบาย |
หมายเลข |
ดัชนีขององค์ประกอบแรกที่ผ่านการทดสอบ มิฉะนั้น -1. |
รองรับเบราว์เซอร์
findIndex()
เป็นคุณลักษณะ ECMAScript6 (ES6)
ES6 (JavaScript 2015) ได้รับการสนับสนุนในเบราว์เซอร์ที่ทันสมัยทั้งหมด:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
findIndex()
ไม่รองรับใน Internet Explorer 11 (หรือเก่ากว่า)
ตัวอย่างเพิ่มเติม
ค้นหาองค์ประกอบแรกที่มีค่าเหนือค่าอินพุต:
<p><input type="number" id="toCheck" value="18"></p>
<button onclick="myFunction()">Test</button>
<p>Any values above: <span id="demo"></span></p>
<script>
const numbers = [4, 12, 16, 20];
function checkValue(x) {
return x > document.getElementById("toCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = numbers.findIndex(checkValue);
}
</script>