Main Page

methods

which returns only the last item,
“yellow”
, and stores it in the variable
vItem
. The array is then left
with only the strings
“red”
and
“green”
.
The
push()
method is actually the same as manually adding the array items as shown in previous
examples. This example could be rewritten as the following:
var stack = new Array;
stack[0] = “red”;
stack[1] = “green”;
stack[2] = “yellow”;
alert(stack.toString()); //outputs “red,green,yellow”
var vItem = stack.pop();
alert(vItem); //outputs “yellow”
alert(stack.toString()); //outputs “red,green”
The
Array
also provides methods to manipulate the very first item. The
shift()
method removes the first
item in the array and returns it as the function value. On the other end of the spectrum, the
unshift()
method places an item into the first position of the array, shifting all other items down one position in the
process. Example:
var aColors = [“red”, “green”, “yellow”];
var vItem = aColors.shift();
alert(aColors.toString()); //outputs “green,yellow”
alert(vItem); //outputs “red”
aColors.unshift(“black”);
alert(aColors.toString()); //outputs “black,green,yellow”
In this example, the string
“red”
is removed (
shift()
ed) from the array, leaving only
“green”
and
“yellow”
. By using the
unshift()
method, the string
“black”
is placed at the front of the array, effec-
tively replacing
“red”
as the new value in the first position.
By using
shift()
and
push()
, it is possible to make an
Array
object behave like a queue. A queue is a
member of the group of data structures that restricts the insertion and removal of elements. A queue is
referred to as a
last-in-last-out
(LILO) structure, meaning that the most recently added element is the last
one removed. The insertion of elements always occurs only at the back of the queue whereas the
removal of elements occurs only at the front of the queue.
When you think of a queue, think of a line at the movies. When new people arrive to get tickets, they go
to the back of the line (Figure 3-3). This is traditionally called
put
or
enqueue
.
Figure 3-3
12345
1234
1234
Star t
Put
Result
5
75
Object Basics
06_579088 ch03.qxd 3/28/05 11:36 AM Page 75


JavaScript EditorFree JavaScript Editor     Ajax Editor


©