Java Reference
In-Depth Information
figure 5-1
Don't forget that the sorting is case sensitive, so Paul will come before paul . Remember that
JavaScript stores letters encoded in their equivalent Unicode number, and that sorting is done based
on Unicode numbers rather than actual letters. It just happens that Unicode numbers match the
order in the alphabet. However, lowercase letters are given a different sequence of numbers, which
come after the uppercase letters. So the array with elements Adam , adam , Zoë , zoë , will be sorted to
the order Adam , Zoë , adam , zoë .
Note that in your for statement you've used the Array object's length property in the condition
statement, rather than inserting the length of the array ( 5 ), like this:
for (var index = 0; index < 5; index++)
Why do this? After all, you know in advance that you have five elements in the array. Well, what
would happen if you altered the number of elements in the array by adding two more names?
var names = [ "Paul", "Sarah", "Jeremy", "Adam", "Bob", "Karen", "Steve" ];
If you had inserted 5 rather than names.length , your loop code wouldn't work as you want it to. It
wouldn't display the last two elements unless you changed the condition part of the for loop to 7 .
By using the length property, you've made life easier, because now there is no need to change code
elsewhere if you add array elements.
Okay, you've put things in ascending order, but what if you wanted descending order? That is where
the reverse() method comes in.
Search WWH ::




Custom Search