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

Array Power, Part I - DHTML Lab | 4

Logo

Array Power, Part I
prototyping unshift()


We can make the unshift() method available to any browser that does not have it built-in, like Explorer, with these JavaScript statements:

if(!Array.prototype.unshift) {
    function array_unshift() {
        this.reverse();
        for(var i=arguments.length-1; i>=0; i--){
            this[this.length] = arguments[i];
        }
        this.reverse();
        return this.length
    }
    Array.prototype.unshift = array_unshift;
}

All Array object methods belong to its prototype object. We therefore check Array.prototype for the existence of an unshift() method. If it does not exist, we proceed to create one. If it exists we do nothing:

if(!Array.prototype.unshift) {
    .
    execute these statements only if
    unshift() does not exist
    .
}

Next, we create a function to represent the unshift() method. It can have any name, but for clarity we will call it array_unshift(). Since this function will be assigned as a method of all arrays, the this keyword in the function refers to the calling array.

Finally, we assign the function to a method of Array.prototype, which we call unshift, in this way creating an unshift() method available to all arrays.

The unshift() method is invoked with a variable number of arguments, so we cannot assign specific variable names to arguments. We can only access them by index in the function's arguments array.

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

Statement usedmyArray becomes
 before method call[0,"cat",true]
1.this.reverse();[true,"cat",0]
2.the for loop cycles through all the arguments passed to the function in reverse order.
That is, first "mouse", then "dog."
One by one, it adds them to the end of the array:
for(var i=arguments.length-1;i>=0;i--){
    this[this.length] = arguments[i];
}

[true,"cat",0,"mouse"]

[true,"cat",0,"mouse","dog"]
3.this.reverse();["dog","mouse",0,"cat",true]
4.return this.length; 

If the above statements are included in a Web page or external JS file, then all Explorer arrays will have an unshift() method.

On the next page, we have an interactive form demonstrating unshift() for both browsers.


Produced by Peter Belesis and

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

URL: https://www.webreference.com/dhtml/column31/4.html