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

เมธอด Array.find() ใน JavaScript

Array.find()

คืน ค่า (Value) แรก ที่ผ่านเงื่อนไข Callback หาไม่เจอ คืน undefined หยุดค้นหาทันทีที่เจอ (Short-circuit)

ไวยากรณ์

arr.find(callback(element[, index[, array]])[, thisArg])

ตัวอย่าง

<html> <body> <p id="demo"></p> <script>
  var price = [3000, 21000, 28000, 20000, 15500];
  
  function checkCost(cost) {
    return cost >= 12000;
  }
  
  document.getElementById('demo').innerHTML = price.find(checkCost);
</script> </body> </html>

ผลลัพธ์

21000

คำอธิบาย

  • 3000 < 12000 → ไม่ผ่าน
  • 21000 ≥ 12000 → ผ่าน! คืน 21000 ทันที
  • 28000, 20000, 15500: ไม่ได้เช็กแล้ว

find() vs findIndex()

MethodReturnNot Found
find()Value (Element)undefined
findIndex()Index (Number)-1

ตัวอย่าง: หา Object ใน Array

const users = [
  {id: 1, name: 'John'},
  {id: 2, name: 'Jane'},
  {id: 3, name: 'Bob'}
];

const user = users.find(u => u.id === 2);
// {id: 2, name: 'Jane'}

const index = users.findIndex(u => u.id === 2);
// 1