Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phương thức Array.prototype.find() trong JavaScript

Phương thức Array.prototype.find() trả về giá trị của phần tử đầu tiên trong mảng thỏa mãn điều kiện được cung cấp. Nếu không tìm thấy phần tử nào, nó trả về undefined.

Cú pháp

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

Ví dụ minh họa

Dưới đây là ví dụ hoàn chỉnh tìm kiếm từ "lion" trong mảng động vật:

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Ví dụ Array.find()</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
        .result { font-size: 20px; font-weight: 500; margin: 10px 0; }
        button { padding: 8px 16px; cursor: pointer; background: #007bff; color: white; border: none; border-radius: 4px; }
        button:hover { background: #0056b3; }
    </style>
</head>
<body>
    <h1>Ví dụ Array.find() trong JavaScript</h1>
    <div class="result" id="arrayDisplay"></div>
    <button id="findBtn">TÌM "LION"</button>
    <h3>Nhấn nút trên để tìm "lion" trong mảng động vật</h3>

    <script>
        const displayEl = document.getElementById('arrayDisplay');
        const animals = ["cow", "lion", "bull", "tiger"];
        
        // Hiển thị mảng ban đầu
        displayEl.textContent = `Mảng gốc: [${animals.join(', ')}]`;
        
        document.getElementById('findBtn').addEventListener('click', () => {
            // Tìm phần tử đầu tiên bằng "lion"
            const found = animals.find(animal => animal === "lion");
            displayEl.innerHTML = `Kết quả find(): ${found}`;
        });
    </script>
</body>
</html>

Kết quả

Ban đầu: Mảng hiển thị đầy đủ: ["cow", "lion", "bull", "tiger"]

Sau khi nhấn nút: Chỉ hiển thị kết quả: lion

Lưu ý quan trọng

  • find() chỉ trả về một phần tử đầu tiên khớp điều kiện.
  • Không làm thay đổi mảng gốc.
  • Nếu cần tìm chỉ số (index), hãy dùng findIndex().
  • Nếu cần tất cả phần tử khớp, dùng filter().