JavaScript Array ทุก ()
ตัวอย่าง 1
ตรวจสอบว่าค่าทั้งหมดในกลุ่มอายุ[] เกิน 18:
const ages = [32, 33, 16, 40];
ages.every(checkAge)
function checkAge(age) {
return age > 18;
}
ตัวอย่าง "ลองใช้เอง" เพิ่มเติมด้านล่าง
ความหมายและการใช้งาน
every()
เมธอดเรียกใช้ฟังก์ชันสำหรับแต่ละองค์ประกอบอาร์เรย์
every()
เมธอดจะคืนค่าหากtrue
ฟังก์ชันคืนค่าเป็นจริงสำหรับองค์ประกอบทั้งหมด
every()
เมธอดจะคืนค่าหากfalse
ฟังก์ชันคืนค่าเป็นเท็จสำหรับองค์ประกอบหนึ่งรายการ
เมธอด นี้every()
ไม่เรียกใช้ฟังก์ชันสำหรับองค์ประกอบว่าง
วิธี การevery()
ไม่เปลี่ยนอาร์เรย์เดิม
ไวยากรณ์
array.every(function(currentValue, index, arr), thisValue)
พารามิเตอร์
Parameter | Description |
function() | Required. A function to be run for each element in the array. |
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. |
คืนมูลค่า
พิมพ์ | คำอธิบาย |
บูลีน |
true หากองค์ประกอบทั้งหมดผ่านการทดสอบ มิfalse ฉะนั้น |
รองรับเบราว์เซอร์
every()
เป็นคุณลักษณะ ECMAScript5 (ES5)
ES5 (JavaScript 2009) รองรับทุกเบราว์เซอร์:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
ตัวอย่างเพิ่มเติม
ตรวจสอบว่าคำตอบทั้งหมดเหมือนกันหรือไม่:
const survey = [
{ name: "Steve", answer: "Yes"},
{ name: "Jessica", answer: "Yes"},
{ name: "Peter", answer: "Yes"},
{ name: "Elaine", answer: "No"}
];
let result = survey.every(isSameAnswer);
function isSameAnswer(el, index, arr) {
if (index === 0) {
return true;
} else {
return (el.answer === arr[index - 1].answer);
}
}
ตรวจสอบว่าค่าทั้งหมดอยู่เหนือจำนวนที่ระบุหรือไม่:
<p><input type="number" id="ageToCheck" value="18"></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.every(checkAge);
}
</script>