23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 6 ■ FUNCTIONS AND ARRAYS<br />

Now append an else clause that has sortByLosses() return -1 if the Pirates lost more games in e1<br />

than e2, and 1 if the Pirates lost more games in e2 than e1:<br />

var pirates = [[2010, 57, 105],<br />

[2009, 62, 99],<br />

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

[2007, 68, 94],<br />

[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 />

var sortByLosses = function (e1, e2) {<br />

if (e1[2] === e2[2]) {<br />

return e1[0] > e2[0] ? -1 : 1;<br />

} else {<br />

return e1[2] > e2[2] ? -1 : 1;<br />

}<br />

};<br />

OK, time to see if sortByLosses() does what we want it to. So invoke sort() on pirates and pass the<br />

sortByLosses identifier—don’t invoke sortByLosses with the () operator or you'll come to grief. sort()<br />

will then reorder and return pirates. So if we invoke console.dir() on the return value of sort(),<br />

JavaScript will print the reordered array in Firebug as Figure 6–33 displays.<br />

var pirates = [[2010, 57, 105],<br />

[2009, 62, 99],<br />

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

[2007, 68, 94],<br />

[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 />

var sortByLosses = function (e1, e2) {<br />

if (e1[2] === e2[2]) {<br />

return e1[0] > e2[0] ? -1 : 1;<br />

241

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

Saved successfully!

Ooh no, something went wrong!