ค้นหาอาร์เรย์ JavaScript ()
ตัวอย่าง 1
ค้นหาค่าขององค์ประกอบแรกที่มีค่ามากกว่า 18:
const ages = [3, 10, 18, 20];
function checkAge(age) {
return age > 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAge);
}
ความหมายและการใช้งาน
วิธี การfind()
คืนค่าขององค์ประกอบแรกที่ผ่านการทดสอบ
find()
เมธอดเรียกใช้ฟังก์ชันสำหรับแต่ละองค์ประกอบอาร์เรย์
find()
เมธอดจะคืนค่าundefined
ใหม่หากไม่พบองค์ประกอบ
เมธอด นี้find()
ไม่เรียกใช้ฟังก์ชันสำหรับองค์ประกอบว่าง
วิธี การfind()
นี้จะไม่เปลี่ยนอาร์เรย์เดิม
ไวยากรณ์
array.find(function(currentValue, index, arr),thisValue)
พารามิเตอร์
function() | Required. A function to 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. |
คืนมูลค่า
พิมพ์ | คำอธิบาย |
ค่า |
ค่าขององค์ประกอบแรกที่ผ่านการทดสอบ มิฉะนั้นจะกลับ undefined มา |
รองรับเบราว์เซอร์
find()
เป็นคุณลักษณะ ECMAScript6 (ES6)
ES6 (JavaScript 2015) ได้รับการสนับสนุนในเบราว์เซอร์ที่ทันสมัยทั้งหมด:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
find()
ไม่รองรับใน Internet Explorer 11 (หรือเก่ากว่า)
ตัวอย่าง 2
ค้นหาค่าขององค์ประกอบแรกที่มีค่าเหนือจำนวนเฉพาะ:
<p><input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const ages = [4, 12, 16, 20];
function checkAge(age) {
return age > document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAge);
}
</script>