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

Array Power, Part II - DHTML Lab | 7

Logo

Array Power, Part II
prototyping pop()


The JavaScript statements necessary for making the pop() method available to any browser that does not have it built-in:

if(!Array.prototype.pop) {
    function array_pop(){
        lastElement = this[this.length-1];
        this.length = Math.max(this.length-1,0);
        return lastElement;
    }
    Array.prototype.pop = array_pop;
}

We first check for the existence of a pop() method, and proceed only if it does not already exist.

Our function representing the pop() method is called array_pop() and is assigned to the pop method of Array.prototype.

Using,
finalGuy = myArray.pop();
here's a step-by-step look at what the function does:

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

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

Finally, an interactive form demonstrating pop() for both browsers.


Produced by Peter Belesis and

All Rights Reserved. Legal Notices.
Created: May 2, 2000
Revised: May 2, 2000

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