Array Power, Part I - DHTML Lab | 7 | WebReference

Array Power, Part I - DHTML Lab | 7


Array Power, Part I
prototyping shift()

To make the shift() method available to any browser that does not have it built-in, we use these JavaScript statements:

if(!Array.prototype.shift) {
    function array_shift() {
        firstElement = this[0];
        this.length = Math.max(this.length-1,0);
        return firstElement;
    Array.prototype.shift = array_shift;

As with our unshift() constructor statements, we first check for the existence of a shift() method, and proceed only if it does not already exist.

The function that represents the shift() method is called array_shift() and the function is assigned to the shift method of Array.prototype. It's now available to all arrays.

Using our example from the previous page,
numeroUno = myArray.shift();
let's take a step-by-step look at what the function does:

Statement usedmyArray becomes
 before method call[0,"cat",true]
1.The first element value is assigned to a variable we call firstElement:
firstElement = this[0];
3.The array is shortened by one element:
this.length = Math.max(this.length-1,0);
5.The first element, which we had assigned before removing is returned:
return firstElement;

If our array has no elements, a value of undefined will be returned. This is a valid value and no error is generated.

Like before we have an interactive form demonstrating shift() for both browsers.

Produced by Peter Belesis and

All Rights Reserved. Legal Notices.
Created: April 26, 2000
Revised: April 26, 2000