Array.length प्रॉपर्टी एरे में तत्वों की संख्या लौटाती है या सेट करती है। यह 0-आधारित इंडेक्सिंग के कारण अंतिम इंडेक्स + 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.length प्रॉपर्टी</h1>
<div class="sample"></div>
<button class="Btn">एरे लंबाई दिखाएं</button>
<h3>ऊपर दिए गए बटन पर क्लिक करके एरे की लंबाई प्राप्त करें</h3>
<script>
const fillEle = document.querySelector(".sample");
const arr = ['H','E','L','L','O'];
fillEle.innerHTML = "एरे: " + arr.join(", ");
document.querySelector(".Btn").addEventListener("click", () => {
fillEle.innerHTML = 'एरे की लंबाई है: ' + arr.length;
});
</script> </body> </html>
आउटपुट
क्लिक करने पर: एरे की लंबाई है: 5
लंबाई सेट करने के प्रभाव
const arr = [1, 2, 3, 4, 5]; // ट्रंकेट (छोटा करना) arr.length = 2; console.log(arr); // [1, 2] // विस्तार (बड़ा करना) - खाली स्लॉट्स बनते हैं arr.length = 5; console.log(arr); // [1, 2, empty × 3] console.log(arr[3]); // undefined console.log(3 in arr); // false (होल है, undefined मान नहीं) // लंबाई 0 = एरे खाली करना arr.length = 0; // []
प्रदर्शन नोट
arr.length = 0 एरे खाली करने का सबसे तेज़ तरीका है (नया एरे बनाने से तेज़ क्योंकि वही रेफरेंस रहता है)।
विरल एरे (Sparse Arrays)
const sparse = []; sparse[100] = "value"; console.log(sparse.length); // 101 (अंतिम इंडेक्स + 1) console.log(sparse[0]); // undefined (लेकिन 0 in sparse → false)
तुलना: length vs गिनती
| एरे | length | वास्तविक तत्व |
|---|---|---|
[1,2,3] | 3 | 3 |
[1,,3] | 3 | 2 (होल) |
[] | 0 | 0 |
new Array(5) | 5 | 0 (सभी होल्स) |