JavaScript Array length Property
The number of elements in a JavaScript array can be retrieved by using the length property of the Array object. Note that this includes any undefined elements.
//Returns 4
var aryTest = [1,2,3,4];
document.write(aryTest.length);
If an element is then added at the 5th position of the array (JavaScript arrays are seeded at 0) the length of the array is 6, even though the 4th position is undefined.
//Returns 6
var aryTest = [1,2,3,4];
aryTest[5] = 5;
document.write(aryTest.length);
So the individual array elements are now:
aryTest[0] = 1
aryTest[1] = 2
aryTest[2] = 3
aryTest[3] = 4
aryTest[4] = undefined
aryTest[5] = 5
From this we can see that the JavaScript array has a length of 6.
The length property of the JavaScript array object can also be used to expand and contract the array.
//Returns 10
var aryTest = [1,2,3,4];
aryTest.length = 10;
document.write(aryTest.length);
The preceding array was initialized to have four elements, then the length property was explicitly set to have 10 elements, which adds six undefined elements to the array.
The length of the array can be similarly contracted.
//Returns 3
var aryTest = [1,2,3,4];
aryTest.length = 3;
document.write(aryTest.length);
In the preceding example, the array is initialized with four elements. When the length is explicitly set to three the fourth element is truncated from the array.
Nice and concise. Keep up the good work.
no, i shall not leave a reply
this works well for arrays with auto-assigned keys etc, but what about arrays using string keys ie Array['key'].. this does not work, also if you have Array[10] and array[100]… there are only 2 keys, but array.length will return 100… So -> thought i’d just share… i can’t seem to find a better method than this…
function array_count(arr) {
var count = 0
for (var i in arr) count++
return count
}
Thanks this was a good read