↑
Main Page
sort
They wait their turns, eventually moving to the front of the line where they buy their tickets. After the
purchase is complete, the people leave the front of the line and go into the movies (Figure 3-4). This is
traditionally called
get
or
dequeue
.
Figure 3-4
Although the names of the methods aren’t the same, the functionality is the same. You add items to the
queue using the
push()
method (adding items to the back of the array) and remove items from the
queue by using the
shift()
method:
var queue = [“red”, “green”, “yellow”];
queue.push(“black”);
alert(queue.toString()); //outputs “red,green,yellow,black”
var sNextColor = queue.shift();
alert(sNextColor); //outputs “red”
alert(queue.toString()); //outputs “green,yellow,black”
In this example, the string
“black”
is added to the back of the queue by using the
push()
method. In
order to get the next color, the
shift()
method is used to retrieve
“red”
, leaving the queue with only
“green”
,
“yellow”
, and
“black”
.
Two methods relate to the ordering of items in arrays, the
reverse()
and
sort()
methods. The
reverse()
method, as one might expect, simply reverses the order of the items in an array. So if you
want to reverse the order of
“red”
,
“green”
,
“blue”
, you do this:
var aColors = [“red”, “green”, “blue”];
aColors.reverse();
alert(aColors.toString()); //outputs “blue,green,red”
The
sort()
method, on the other hand, arranges the item in the array by sorting them into ascending
order based on their values. To do this sort, transform all values into strings by calling their
toString()
method. The items are compared by character code (as I described in the section on using the less-than
operator on strings). For example:
var aColors = [“red”, “green”, “blue”, “yellow”];
aColors.sort();
alert(aColors.toString()); //outputs “blue,green,red,yellow”
234
2 34
1234
Star t
Get
Result
1
76
Chapter 3
06_579088 ch03.qxd 3/28/05 11:36 AM Page 76
Free JavaScript Editor
Ajax Editor
©
→ R7