|
| |
Total number of elements in an array using length property |
We can find the length or size of any JavaScript array by using its length property. To access the elements of the array we can use this length property to loop through. Please note that first element of an array starts from 0 so array_name[1] is the second element of the array where as array_name[0] is the first element of the array. Same way the last element of the array is the total size of the array minus one. We will see example of this here.
Let us start with a simple array consisting of some scripting languages ( or any thing of your choice )
<script type="text/javascript">
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
document.write(scripts.length);
</script>
You can see the above code will display error message saying undefined. Why ?
The reason is we are trying to display beyond the last element of the array. So the last element of the array can be accessed by not (scripts.length) but by (scripts.lenght -1)
So the correct code is here to display the last element of an array
<script type="text/javascript"> var scripts = new Array(); scripts[0] = "PHP"; scripts[1] = "ASP"; scripts[2] = "JavaScript"; scripts[3] = "HTML"; document.write(scripts[scripts.length-1]); </script>
This will display HTML as last element of the array
Assigning Array length property value
What happens when we assign a value to length property of the array which is less than the actual size ( or length ) of the array?
The elements after the assigned length are lost!
Let us see this example where after storing four elements in the array we will limit the length value of the array to 2 and see what happens.
<script type="text/javascript">
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
document.write(scripts[scripts.length-1]); // Print HTML
scripts.length=2;
document.write("<br>"); // One line break
document.write(scripts[scripts.length-1]); // Print ASP
</script>
We lost last two elements of the array by assigning less value to the array length property.
| |
| Subscribe |
|
Submit your email address and receive
article and product notifications. Your email is safe with us.
|
|
|
|