Moving through arrays

You can cycle through an array that has been created in order to change it, gain information from it, or list its content.

var StudentsNames = new Array();
StudentsNames[0] = "Dan";
StudentsNames[1] = "Tra";
StudentsNames[2] = "Sonia";
StudentsNames[3] = "Flora";

for (var count=0; count<StudentsNames.length; count++) {
	document.write(StudentsNames[count]+ "<br>");
}

First line creates the new array then on lines 2-5 each element of the new array is assigned a value. The for loop is used to print on the screen the elements of the array.

The use of cont<StudentsName.lenght is beneficial since the array can be adjusted to any number of elements. The loop will cycle through until the full array is used.

If you want the array sorted in alphabetical number then just add StudentsNames.sort(); to your code just after the last element of the array.

An easier way of achieving the same result:

var StudentsNames = new Array();
StudentsNames[0] = "Dan";
StudentsNames[1] = "Tra";
StudentsNames[2] = "Sonia";
StudentsNames[3] = "Flora";

for (student in StudentsNames) {
	document.write(StudentsNames[student] + "<br>");
}

Leave a Reply