जावास्क्रिप्ट का array.includes() मेथड चेक करने के लिए उपयोग किया जाता है कि क्या एरे में एक निर्दिष्ट एलिमेंट है।
सिंटैक्स इस प्रकार है:
array.includes(element, fromIndex)
ऊपर, पैरामीटर element खोजने के लिए एलिमेंट है। fromIndex पैरामीटर वह पोजीशन है जहां से खोज शुरू करनी है।
उदाहरण 1
<!DOCTYPE html>
<html>
<body>
<h2>कार वेरिएंट</h2>
<button onclick="display()">परिणाम</button>
<p id="test"></p>
<script>
var carid = ["110", "230", "299", "399"];
document.getElementById("test").innerHTML = carid;
function display() {
var n = carid.includes("230");
document.getElementById("test").innerHTML = "The array has the specific value 230? = " + n;
}
</script>
</body>
</html>
आउटपुट
true
उदाहरण 2
<!DOCTYPE html>
<html>
<body>
<h2>कार वेरिएंट</h2>
<p>क्या एरे में विशिष्ट एलिमेंट Crossover शामिल है?</p>
<button onclick="display()">परिणाम</button>
<p id="test"></p>
<script>
var car = ["Hatchback", "Convertible"];
var res2 = car.entries();
for (val of res2) {
document.getElementById("test").innerHTML += val + "<br>";
}
function display() {
var res = car.includes("Crossover");
document.getElementById("test").innerHTML = res;
}
</script>
</body>
</html>
आउटपुट
false
विस्तृत उपयोग
const arr = [1, 2, 3, 4, 5];
// बेसिक उपयोग
arr.includes(3); // true
arr.includes(6); // false
// fromIndex के साथ
arr.includes(2, 2); // false (इंडेक्स 2 से शुरू - 3,4,5 चेक करता है)
arr.includes(2, -1); // false (अंतिम एलिमेंट से - 5 चेक करता है)
arr.includes(5, -1); // true
// NaN हैंडलिंग (indexOf के विपरीत)
[NaN].includes(NaN); // true ✓
[NaN].indexOf(NaN); // -1 ✗
// ऑब्जेक्ट्स (रेफरेंस तुलना)
const obj = { a: 1 };
[{ a: 1 }].includes(obj); // false - अलग रेफरेंस
const arr2 = [obj];
arr2.includes(obj); // true - समान रेफरेंस
includes vs indexOf vs some
const arr = [1, 2, 3];
arr.includes(2); // true - बूलियन, पठनीय
arr.indexOf(2) !== -1; // true - पुराना तरीका
arr.some(x => x === 2); // true - फ्लेक्सिबल कंडीशन
// प्रदर्शन: includes ≈ indexOf > some (सिंपल केस के लिए)
नोट: includes ES2016 (ES7) में जोड़ा गया। पुराने ब्राउज़र्स के लिए पॉलीफिल आवश्यक हो सकता है।