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

Array Power, Part I - DHTML Lab | 7

Logo

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.reverse();
        this.length = Math.max(this.length-1,0);
        this.reverse();
        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];
 
2.this.reverse();[true,"cat",0]
3.The array is shortened by one element:
this.length = Math.max(this.length-1,0);
[true,"cat"]
4.this.reverse();["cat",true]
5.The first element, which we had assigned before removing is returned:
return firstElement;
 

Note:
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

URL: http://www.webreference.com/dhtml/column31/7.html