Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Array.prototype.find() ใน JavaScript หา Element แรกที่ตรงเงื่อนไข

Array.find(callback) คืน Element แรก ที่ Callback คืน true ไม่พบคืน undefined

ตัวอย่าง

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Array Find</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .find { font-size: 20px; font-weight: 500; }
  </style>
</head>
<body>
  <h1>JavaScript Array Find() Example</h1>
  <div class="find"></div>
  <button class="fillArr">CLICK HERE</button>
  <h3> Click to find 'lion' in animals </h3>
  <script>
    function findLion(animal) { return animal === "lion"; }
    let fillEle = document.querySelector(".find");
    let arr = ["cow", "lion", "bull", "tiger"];
    fillEle.innerHTML = arr;
    document.querySelector(".fillArr").addEventListener("click", () => {
      fillEle.innerHTML = "Found: " + arr.find(findLion);
    });
  </script>
</body>
</html>

คำอธิบาย

  • arr.find(fn) หาตัวแรกที่ fn คืน true
  • Callback: fn(element, index, array)
  • ต่าง filter(): filter คืน Array ทุกตัวที่ Match, find คืนแค่ตัวแรก
  • ต่าง indexOf(): indexOf หาค่า Exact, find หาโดย Condition/Function
  • คู่คือ findIndex() คืน Index แทน Element

ผลลัพธ์

ก่อน: cow,lion,bull,tiger | หลัง: Found: lion