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 4 ■ CONTROLLING FLOW<br />

138<br />

"Jokinen": 30,<br />

"Kane": 30<br />

};<br />

var rocketRichard = ["Ovechkin", "Crosby", "Marleau", "Stamkos"], note = "";<br />

Now let’s order the names in rocketRichard by goals and then by name. To do so, we will use the<br />

sort() method that every array, including rocketRichard, defines so that you can order its elements. We<br />

will cover sort() and other Array methods in the next chapter. So for now, just type carefully!<br />

var topTwenty = {<br />

"Crosby": 49,<br />

"Ovechkin": 48,<br />

"Stamkos": 48,<br />

"Marleau": 43,<br />

"Gaborik": 41,<br />

"Kovalchuk": 40,<br />

"Heatley": 39,<br />

"Semin": 39,<br />

"Parise": 37,<br />

"Burrows": 35,<br />

"Kopitar": 34,<br />

"Ryan": 34,<br />

"Carter": 33,<br />

"Nash": 33,<br />

"Iginla": 32,<br />

"Penner": 32,<br />

"Backstrom": 31,<br />

"Hornqvist": 30,<br />

"Jokinen": 30,<br />

"Kane": 30<br />

};<br />

var rocketRichard = ["Ovechkin", "Crosby", "Marleau", "Stamkos"], note = "";<br />

rocketRichard.sort(function(p1, p2) {<br />

var d = topTwenty[p2] - topTwenty[p1];<br />

if (d !== 0) {<br />

return d;<br />

} else {<br />

return (p1 < p2) ? -1 : 1;<br />

}<br />

});<br />

Now we can code either a for, while, or do while loop to indirectly enumerate members in<br />

topTwenty by way of the member names in rocketRichard. Let’s go with a for loop. This one will build up<br />

a string in note that lists the top four goal scorers. Following the for loop, let’s clip off the ", " from the<br />

end of note with String.slice(), a method we covered in Chapter 2. Then click Run, and verify your work<br />

with Figure 4–17.<br />

var topTwenty = {<br />

"Crosby": 49,<br />

"Ovechkin": 48,<br />

"Stamkos": 48,<br />

"Marleau": 43,<br />

"Gaborik": 41,<br />

"Kovalchuk": 40,

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

Saved successfully!

Ooh no, something went wrong!