18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

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.

Chapter 3<br />

They wait their turns, eventually moving to the front of the line where they buy their tickets. After the<br />

purchase is complete, the people leave the front of the line and go into the movies (Figure 3-4). This is<br />

traditionally called get or dequeue.<br />

Start<br />

1 2 3 4<br />

Get<br />

1<br />

2 3 4<br />

Figure 3-4<br />

Result<br />

2 3 4<br />

Although the names of the methods aren’t the same, the functionality is the same. You add items to the<br />

queue using the push() method (adding items to the back of the array) and remove items from the<br />

queue by using the shift() method:<br />

var queue = [“red”, “green”, “yellow”];<br />

queue.push(“black”);<br />

alert(queue.toString());<br />

//outputs “red,green,yellow,black”<br />

var sNextColor = queue.shift();<br />

alert(sNextColor);<br />

//outputs “red”<br />

alert(queue.toString());<br />

//outputs “green,yellow,black”<br />

In this example, the string “black” is added to the back of the queue by using the push() method. In<br />

order to get the next color, the shift() method is used to retrieve “red”, leaving the queue with only<br />

“green”, “yellow”, and “black”.<br />

Two methods relate to the ordering of items in arrays, the reverse() and sort() methods. The<br />

reverse() method, as one might expect, simply reverses the order of the items in an array. So if you<br />

want to reverse the order of “red”, “green”, “blue”, you do this:<br />

var aColors = [“red”, “green”, “blue”];<br />

aColors.reverse();<br />

alert(aColors.toString()); //outputs “blue,green,red”<br />

The sort() method, on the other hand, arranges the item in the array by sorting them into ascending<br />

order based on their values. To do this sort, transform all values into strings by calling their toString()<br />

method. The items are compared by character code (as I described in the section on using the less-than<br />

operator on strings). <strong>For</strong> example:<br />

var aColors = [“red”, “green”, “blue”, “yellow”];<br />

aColors.sort();<br />

alert(aColors.toString()); //outputs “blue,green,red,yellow”<br />

76

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

Saved successfully!

Ooh no, something went wrong!