Array.includes() मेथड जांचता है कि कोई एरे दिए गए तत्व को शामिल करता है या नहीं, और true या false लौटाता है। यह indexOf() !== -1 से अधिक पठनीय है।
उदाहरण
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
.sample { font-size: 20px; font-weight: 500; }
button { padding: 10px 20px; background: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style> </head> <body>
<h1>JavaScript Array.includes() मेथड</h1>
<div class="sample"></div>
<button class="Btn">जांचें: शेर एरे में है?</button>
<h3>ऊपर दिए गए बटन पर क्लिक करके जांचें कि एरे में 'शेर' तत्व है या नहीं</h3>
<script>
const fillEle = document.querySelector(".sample");
const arr = ["गाय", "बैल", "शेर", "बाघ", "भेड़"];
fillEle.innerHTML = "एरे: " + arr.join(", ");
document.querySelector(".Btn").addEventListener("click", () => {
fillEle.innerHTML = "शेर एरे में मौजूद है: " + arr.includes("शेर");
});
</script> </body> </html>
आउटपुट
क्लिक करने पर: शेर एरे में मौजूद है: true
सिंटैक्स और पैरामीटर्स
arr.includes(searchElement, fromIndex)
searchElement- खोजने वाला तत्वfromIndex(वैकल्पिक) - खोज शुरू करने का इंडेक्स (डिफ़ॉल्ट: 0), ऋणात्मक मान अंत से गिनता है
includes() vs indexOf()
| विशेषता | includes() | indexOf() |
|---|---|---|
| लौटाता है | Boolean | इंडेक्स (-1 यदि नहीं मिला) |
| NaN खोज | ✅ काम करता है | ❌ NaN नहीं खोजता |
| पठनीयता | उच्च | कम |
| केस सेंसिटिव | हां | हां |
NaN उदाहरण
[1, 2, NaN].includes(NaN); // true [1, 2, NaN].indexOf(NaN); // -1 (गलत!)