array.length
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.
<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>
Output of above code is 4
<script type="text/javascript">
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
document.write(scripts.length);
document.write(scripts[scripts.length]);
</script>
You can see the above code will display error message saying undefined. Why ?
<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
<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.
<script type="text/javascript">
var str="Welcome to plus2net. You can learn web programming and use them in your applications";
var a1 = new Array();
a1=str.split(" ");
document.write("total Number of words present: "+ a1.length);
</script>
Output is here
total Number of words present: 14
Array ReferenceHow to display elements of an Array
Gabriel | 09-03-2013 |
How do you get this to work? |