HTML and CSS Reference
In-Depth Information
JavaScript doesn't natively provide a custom object to represent specialized collections or
arrays. Instead, methods are provided on the
Array
object that allows you to implement
various types of specialized collections such as a queue or a stack.
A queue is essentially a first-in-first-out type of collection. Whenever items are added to
the list, they should go at the end of the line. In contrast, a is a last-in-first-out type of collec-
tion in which the last item put on the stack is the first item you can take out of the stack. The
array methods that facilitate this type of behavior are
pop
,
push
,
shift
, and
unshift
.
Using the
pop
and
push
methods
The
pop
and
push
methods provide stack functionality. The
push
method appends the speci-
fied items to the end of the array. The
pop
method removes the last item from the array. The
following code demonstrates the
push
method:
var sports = new Array();
sports.push('soccer', 'basketball', 'hockey');
sports.push('football');
This code creates an
Array
object, and then inserts (pushes) three items into the array.
The items are added to the stack in the same order in which they appear in the parameter
list. Next, the code pushes one additional item onto the stack. The
pop
method removes and
returns the last item in the array:
var nextSport = sports.pop();
When this code runs, the
nextSport
variable holds the value 'football' because that was the
last value added to the array.
NOTE
USING
PUSH
AND
POP
ON ANY ARRAY
You can use the
pop
and
push
methods in any context to add and remove items from the
end of an array. The stack concept is useful but isn't a confining mechanism that limits use
of these methods to just stack arrays.
Using the
shift
and
unshift
methods
The
shift
and
unshift
methods work in the exact opposite way from the
pop
and
push
methods. The
shift
method removes and returns the first element of the array, whereas the
unshift
method inserts new elements at the beginning of the array. The following code uses
the
shift
and
unshift
methods:
var sports = new Array();
sports.unshift('soccer', 'basketball', 'hockey');
sports.unshift('football');
var nextSport = sports.shift();
Search WWH ::
Custom Search