34,333
edits
Changes
→JavaScript Array Sorting
<pre>
var myColors = new Array ("Red, "Green", "Blue", "Indigo", "Violet");
for (i in myColors)
{
document.write ("myColor[" + i + "] = " + myColors[i] + "<br>" );
}
</pre>
will output the colors in the order in which we added them to the array:
myColor[0] = Red
myColor[1] = Green
myColor[2] = Blue
myColor[3] = Indigo
myColor[4] = Violet
If we sort the array using the sort() method before printing out the element however:
<pre>
var myColors = new Array ("Red, "Green", "Blue", "Indigo", "Violet");
myColors.sort();
for (i in myColors)
{
document.write ("myColor[" + i + "] = " + myColors[i] + "<br>" );
}
</pre>
we get the following output with the colors sorted alphabetically:
myColor[0] = Blue
myColor[1] = Green
myColor[2] = Indigo
myColor[3] = Red
myColor[4] = Violet