Wednesday, July 1, 2009

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.

Source : http://blog.techsaints.com/2007/04/28/javascript-array-length-property/

No comments:

Post a Comment