Kiểm tra phần tử trong mảng với includes()
Array.prototype.includes() (ES2016/ES7) kiểm tra xem mảng có chứa một phần tử cụ thể hay không, trả về true hoặc false. Đây là cách trực quan hơn so với indexOf() !== -1.
Cú pháp
arr.includes(searchElement[, fromIndex])
searchElement: Giá trị cần tìm.fromIndex(tùy chọn): Vị trí bắt đầu tìm (mặc định 0). Giá trị âm tính từ cuối mảng.
Ví dụ minh họa
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Array includes()</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.sample { font-size: 20px; font-weight: 500; font-family: monospace; }
button { padding: 8px 16px; cursor: pointer; }
</style>
</head>
<body>
<h1>JavaScript Array includes()</h1>
<div class="sample"></div>
<button class="btn-demo">KIỂM TRA</button>
<h3>Nhấn nút để kiểm tra mảng có chứa "lion" không</h3>
<script>
const fillEle = document.querySelector(".sample");
const btn = document.querySelector(".btn-demo");
const arr = ["bò", "bò đực", "sư tử", "hổ", "cừu"];
fillEle.textContent = 'Mảng: ' + JSON.stringify(arr);
btn.addEventListener("click", () => {
const hasLion = arr.includes("sư tử");
fillEle.textContent = 'Mảng chứa "sư tử": ' + hasLion;
});
</script>
</body>
</html>
Đặc điểm nổi bật so với indexOf()
| Đặc điểm | includes() | indexOf() |
|---|---|---|
| Trả về | true/false | Index (số) hoặc -1 |
| Tìm NaN | ✓ [NaN].includes(NaN) === true | ✗ [NaN].indexOf(NaN) === -1 |
| Dấu 0 | Phân biệt +0 và -0 | Coi +0 === -0 |
| Đọc code | Ngữ nghĩa rõ ràng | Cần so sánh !== -1 |
Ví dụ với fromIndex
const arr = ['a', 'b', 'c', 'a', 'b'];
arr.includes('a'); // true
arr.includes('a', 1); // true (tìm từ index 1, tìm thấy ở index 3)
arr.includes('a', 4); // false (tìm từ index 4, chỉ còn 'b')
arr.includes('b', -2); // true (tìm từ 2 phần tử cuối: 'a', 'b')
arr.includes('a', -2); // true
arr.includes('c', -2); // false
So sánh với Set.has()
const arr = [1, 2, 3, 4, 5];
const set = new Set(arr);
// Kiểm tra đơn lẻ: includes() OK
arr.includes(3); // true
// Kiểm tra nhiều lần: Set.has() nhanh hơn O(1)
function checkMultiple(arr, values) {
const set = new Set(arr);
return values.every(v => set.has(v));
}
Lưu ý
- Sử dụng thuật toán SameValueZero (gần như === nhưng NaN === NaN).
- Không tìm thấy trong prototype chain.
- Hỗ trợ: Chrome 47+, Firefox 43+, Safari 9+, Edge 14+.