เมธอด find() ใช้สำหรับ คืนค่าองค์ประกอบแรก ในอาร์เรย์ที่ทำให้ฟังก์ชันทดสอบ (callback) คืนค่า true หากไม่พบจะคืนค่า undefined
ไวยากรณ์ (Syntax)
array.find(callback(element[, index[, array]])[, thisArg])
ตัวอย่างการใช้งาน
ตัวอย่างที่ 1: หาคะแนนแรกที่มากกว่า 400
<!DOCTYPE html>
<html>
<body>
<h2>คะแนนอันดับ</h2>
<p>หาคะแนนแรกที่มากกว่า 400...</p>
<button onclick="display()">ค้นหา</button>
<p id="demo"></p>
<script>
const pointsArr = [50, 100, 200, 300, 400, 500, 600];
function pointsFunc(points) {
return points > 400;
}
function display() {
const result = pointsArr.find(pointsFunc);
document.getElementById("demo").innerHTML = result;
// ผลลัพธ์: 500
}
</script>
</body>
</html>
ตัวอย่างที่ 2: ไม่พบองค์ประกอบที่ตรงเงื่อนไข (คืนค่า undefined)
<!DOCTYPE html>
<html>
<body>
<h2>คะแนนอันดับ</h2>
<p>หาคะแนนแรกที่มากกว่า 400... (ไม่มีในอาร์เรย์)</p>
<button onclick="display()">ค้นหา</button>
<p id="demo"></p>
<script>
const pointsArr = [50, 100, 200, 300, 400]; // ไม่มีค่า > 400
function pointsFunc(points) {
return points > 400;
}
function display() {
const result = pointsArr.find(pointsFunc);
document.getElementById("demo").innerHTML = result;
// ผลลัพธ์: undefined
}
</script>
</body>
</html>
ความแตกต่างระหว่าง find, findIndex, filter
| เมธอด | คืนค่า | หยุดเมื่อพบตัวแรก | กรณีไม่พบ |
|---|---|---|---|
find() | องค์ประกอบ | ใช่ | undefined |
findIndex() | ดัชนี (Number) | ใช่ | -1 |
filter() | อาร์เรย์ใหม่ (ทุกตัวที่ตรง) | ไม่ | [] (อาร์เรย์ว่าง) |
การใช้งานกับอ็อบเจกต์ในอาร์เรย์
const users = [
{id: 1, name: "John", age: 25},
{id: 2, name: "Jane", age: 30},
{id: 3, name: "Bob", age: 25}
];
// หาผู้ใช้คนแรกที่อายุ 25
const user = users.find(u => u.age === 25);
console.log(user); // {id: 1, name: "John", age: 25}
// หาดัชนีแทน
const index = users.findIndex(u => u.age === 25);
console.log(index); // 0