เมธอด includes() ใช้สำหรับ ตรวจสอบว่าอาร์เรย์มีค่าที่ระบุอยู่หรือไม่ คืนค่า true หรือ false ใช้งานง่ายกว่า indexOf()
ไวยากรณ์ (Syntax)
array.includes(searchElement[, fromIndex])
searchElement- ค่าที่ต้องการค้นหาfromIndex(ตัวเลือก) - ดัชนีเริ่มต้นค้นหา (ค่าเริ่มต้น: 0) ค่าลบ = นับจากท้าย
ตัวอย่างการใช้งาน
ตัวอย่างที่ 1: ค้นหาค่าในอาร์เรย์สตริง
<!DOCTYPE html>
<html>
<body>
<h2>รหัสรถยนต์</h2>
<button onclick="display()">ตรวจสอบ</button>
<p id="demo"></p>
<script>
const carid = ["110", "230", "299", "399"];
document.getElementById("demo").innerHTML = "อาร์เรย์: " + carid;
function display() {
const has230 = carid.includes("230");
document.getElementById("demo").innerHTML =
"อาร์เรย์: " + carid + "<br>" +
"มีค่า '230' หรือไม่? = " + has230;
// ผลลัพธ์: true
}
</script>
</body>
</html>
ตัวอย่างที่ 2: ค้นหาที่ไม่มีในอาร์เรย์
<!DOCTYPE html>
<html>
<body>
<h2>รูปแบบรถยนต์</h2>
<p>อาร์เรย์มี 'Crossover' หรือไม่?</p>
<button onclick="display()">ตรวจสอบ</button>
<p id="demo"></p>
<script>
const car = ["Hatchback", "Convertible"];
// แสดง entries ก่อน
const entries = car.entries();
for (const val of entries) {
document.getElementById("demo").innerHTML += val + "<br>";
}
function display() {
const hasCrossover = car.includes("Crossover");
document.getElementById("demo").innerHTML = "มี 'Crossover' หรือไม่? = " + hasCrossover;
// ผลลัพธ์: false
}
</script>
</body>
</html>
ความสามารถพิเศษ: รองรับ NaN
// includes() หา NaN ได้! (indexOf หาไม่ได้) [NaN, 1, 2].includes(NaN); // true ✅ [NaN, 1, 2].indexOf(NaN); // -1 ❌
พารามิเตอร์ fromIndex
const arr = ['a', 'b', 'c', 'a', 'b'];
arr.includes('a'); // true (ค้นหาตั้งแต่ต้น)
arr.includes('a', 1); // true (ค้นหาตั้งแต่ดัชนี 1 พบที่ดัชนี 3)
arr.includes('a', 4); // false (ค้นหาตั้งแต่ดัชนี 4 ไม่พบ)
arr.includes('b', -2); // true (ค้นหาย้อนหลัง 2 ตัว พบ 'b' ตัวสุดท้าย)
arr.includes('c', -3); // true (ค้นหาย้อนหลัง 3 ตัว พบ 'c')
เปรียบเทียบ includes() vs indexOf() vs some()
| เมธอด | คืนค่า | หา NaN ได้ | รองรับ fromIndex | ใช้เมื่อ |
|---|---|---|---|---|
includes() | Boolean | ✅ ใช่ | ✅ ใช่ | แค่ต้องการรู้ว่ามี/ไม่มี |
indexOf() | Number (index) | ❌ ไม่ได้ | ✅ ใช่ | ต้องการดัชนี |
some() | Boolean | ✅ ใช่ | ❌ ไม่ได้ | เงื่อนไขซับซ้อน (callback) |
กรณีใช้งานจริง
// ตรวจสอบสิทธิ์
const userRoles = ['admin', 'editor'];
const canDelete = userRoles.includes('admin'); // true
// Feature flags
const enabledFeatures = ['dark-mode', 'beta-ui'];
if (enabledFeatures.includes('dark-mode')) {
// เปิด dark mode
}
// ตรวจสอบค่าที่อนุญาต
const allowedOrigins = ['https://app.com', 'https://dev.app.com'];
const isAllowed = allowedOrigins.includes(requestOrigin);