The length of any Javascript array can be found by using its length property. Moreover, the length property can be used to loop through array elements. Array numbering starts from 0 in Javascript. Therefore, name_of_the_array[1] is the second element of the array. As a result, the last element of the array is the total size of the array minus 1.
var myarray = ['a', 'b', 'c', 'd'];
Getting the first element of a Javascript Array:
document.write(myarray[0]);
This will display a as the first element of the array.
Getting the last element of a Javascript Array:
document.write(myarray[myarray.lenth-1]);
This will display d as the last element of the array.
Looping through the elements of a Javascript Array:
var myarray = ['a', 'b', 'c', 'd'];
for(i=0;i {
document.write(myarray[i]);
}
This will display abcd.
Assigning a value to Javascript Array Length Property
If we assign a value to length property of the array which is less than the actual length of the array, the elements after the assigned length are lost.
Check the following example:
var myarray = ['a', 'b', 'c', 'd'];
myarray.length=2;
document.write(myarray[myarray.lenth-1]);
We lost the last two elements by assigning a value smaller than the actual length of the array. Therefore, the example above will display b.
Array Length Browser Incompatiblity
The following code returns 4 in Firefox and 5 in IE.
var myarray = ['a', 'b', 'c', 'd',];
document.write(foo.length);
The extra comma on the end of the array causes the interpretation difference. IE interprets this as an additional element with an undefined value. Firefox ignores it.
The ECMAScript standard says:
Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined.
According to the standard the interpretation of IE is correct. However, you have to be careful to write your code compatible to all browsers.
Currently rated 4.3 by 6 people
- Currently 4.333333/5 Stars.
- 1
- 2
- 3
- 4
- 5