ตัวกรองอาร์เรย์ JavaScript ()
ตัวอย่าง 1
ส่งกลับอาร์เรย์ของค่าทั้งหมดในวัย[]ที่อายุ 18 ปีขึ้นไป:
const ages = [32, 33, 16, 40];
const result = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
ความหมายและการใช้งาน
วิธี การfilter()
สร้างอาร์เรย์ใหม่ที่เต็มไปด้วยองค์ประกอบที่ผ่านการทดสอบโดยฟังก์ชัน
เมธอด นี้filter()
ไม่เรียกใช้ฟังก์ชันสำหรับองค์ประกอบว่าง
วิธี การfilter()
นี้จะไม่เปลี่ยนอาร์เรย์เดิม
ไวยากรณ์
array.filter(function(currentValue, index, arr), thisValue)
พารามิเตอร์
Parameter | Description |
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. |
คืนมูลค่า
พิมพ์ | คำอธิบาย |
อาร์เรย์ |
ประกอบด้วยองค์ประกอบที่ผ่านการทดสอบ หากไม่มีองค์ประกอบใดผ่านการทดสอบ จะส่งกลับอาร์เรย์ที่ว่างเปล่า |
รองรับเบราว์เซอร์
filter()
เป็นคุณลักษณะ ECMAScript5 (ES5)
ES5 (JavaScript 2009) รองรับทุกเบราว์เซอร์:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
ตัวอย่าง 2
ส่งกลับค่าในวัย[]ที่มากกว่าจำนวนที่ระบุ:
<p><input type="number" id="ageToCheck" value="30"></p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const ages = [32, 33, 12, 40];
function checkAge(age) {
return age > document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.filter(checkAge);
}
</script>