Main Page

functionality

Figure 3-1
Figure 3-2
To facilitate such functionality, the
Array
object provides two methods,
push()
and
pop()
. As you
might expect, the
push()
method adds one or more items to the end of the
Array
whereas the
pop()
method removes the very last item (
length – 1
) from the array and returns it as the function value.
Consider the following example:
var stack = new Array;
stack.push(“red”);
stack.push(“green”);
stack.push(“yellow”);
alert(stack.toString()); //outputs “red,green,yellow”
var vItem = stack.pop();
alert(vItem); //outputs “yellow”
alert(stack.toString()); //outputs “red,green”
In the previous code, an empty
Array
object is created and then populated by using the
push()
method
numerous times (note that even though this example shows only one argument for the
push()
method,
you can, in fact, pass as many arguments as you wish). After the array is filled, the string value is output
(
“red,green,yellow”
) to assure that all items have been added. Then, the
pop()
method is called,
3
1
0
3
2
1
0
2
1
0
2
top
bottom
Pop off the stack
4
1
0
3
2
1
0
3
2
4
1
0
3
2
top
bottom
Push onto the stack
74
Chapter 3
06_579088 ch03.qxd 3/28/05 11:36 AM Page 74


JavaScript EditorFree JavaScript Editor     Ajax Editor


©

R7