23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

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

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

[2006, 67, 95],<br />

[2005, 67, 95],<br />

[2004, 72, 89],<br />

[2003, 75, 87],<br />

[2002, 72, 89],<br />

[2001, 62, 100],<br />

[2000, 69, 93],<br />

[1999, 78, 83],<br />

[1998, 69, 93],<br />

[1997, 79, 83],<br />

[1996, 73, 89],<br />

[1995, 58, 86],<br />

[1994, 53, 61],<br />

[1993, 75, 87]];<br />

console.dir(pirates[0]);<br />

pirates.reverse();<br />

console.dir(pirates[0]);<br />

Figure 6–32. Reversing the order of elements in an array by invoking its reverse() method<br />

Sorting the Elements in an Array<br />

CHAPTER 6 ■ FUNCTIONS AND ARRAYS<br />

Though reversing the order of elements in pirates is interesting, it would be more helpful if we could<br />

reorder those by wins or losses. To do so, we’d invoke sort() on pirates and pass a function value to do<br />

the reordering work. JavaScript will pass that function two elements from pirates—yup, happens by<br />

magic—and the function will then return -1 if the first element ought to come before the second<br />

element, 0 if there is a tie, and 1 if the second element ought to come before the first element. Though<br />

it’s typical for the function to return -1 and 1, any negative or positive integer will do. The only return<br />

value set in stone is 0, which conveys a tie.<br />

239

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

Saved successfully!

Ooh no, something went wrong!