04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5: Reference Types<br />

Reordering Methods<br />

Two methods deal directly with the reordering of items already in the array: reverse() and sort() . As<br />

one might expect, the reverse() method simply reverses the order of items in an array. Take this code<br />

for example:<br />

var values = [1, 2, 3, 4, 5];<br />

values.reverse();<br />

alert(values); //5,4,3,2,1<br />

Here, the array values has its items initially set to 1, 2, 3, 4, and 5, in that order. Calling reverse() on<br />

the array reverses the order to 5, 4, 3, 2, 1. This method is fairly straightforward but doesn ’ t provide<br />

much flexibility, which is where the sort() method comes in.<br />

By default, the sort() method puts the items in ascending order — with the smallest value first and the<br />

largest value last. To do this, the sort() method calls the String() casting function on every item and<br />

then compares the strings to determine the correct order. This occurs even if all items in an array are<br />

numbers, as in this example:<br />

var values = [0, 1, 5, 10, 15];<br />

values.sort();<br />

alert(values); //0,1,10,15,5<br />

Even though the values in this example begin in correct numeric order, the sort() method changes that<br />

order based on their string equivalents. So even though 5 is less than 10, the string “ 10 ” comes before<br />

“ 5 ” when doing a string comparison, so the array is updated accordingly. Clearly this is not an optimal<br />

solution in many cases, so the sort() method allows you to pass in a comparison function that indicates<br />

which value should come before which.<br />

A comparison function accepts two arguments and returns a negative number if the first argument<br />

should come before the second, a zero if the arguments are equal, or a positive number if the first<br />

argument should come after the second. Here ’ s an example of a simple comparison function:<br />

function compare(value1, value2) {<br />

if (value1 < value2) {<br />

return -1;<br />

} else if (value1 > value2) {<br />

return 1;<br />

} else {<br />

return 0;<br />

}<br />

}<br />

106

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!