Array Power, Part III - DHTML Lab | 11 | WebReference

Array Power, Part III - DHTML Lab | 11

Logo

Array Power, Part III
prototyping splice()


As mentioned, the splice() prototyping code should be available, not only to Explorer, but to versions of Navigator that have the old splice() method, and to scripts running under LANGUAGE=JavaScript1.2. When we have finished prototyping splice() all instances of splice() will behave the same way regardless of the browser environment:

if(Array.prototype.splice && typeof([0].splice(0))=="number")
    Array.prototype.splice = null;
if(!Array.prototype.splice) {
    function array_splice(ind,cnt){
        removeArray = this.slice(ind,ind+cnt);
        endArray = this.slice(ind+cnt);
        this.length = ind;
        for(var i=2;i<arguments.length;i++){
            this[this.length] = arguments[i];
        }
        for(var i=0;i<endArray.length;i++){
            this[this.length] = endArray[i];
        }
        return removeArray;
    }
    Array.prototype.splice = array_splice;
}

We first check Array.prototype for the existence of an splice() method. If it does not exist, we proceed to create one (Explorer and JS1.2 behavior in Navigator). If it exists we do nothing (Navigator JS1.3 behavior):

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

Our function to represent the new splice() method is called array_splice() and we assign it to the splice method of Array.prototype, making it available to all arrays in both browsers.

This is what the function does, step by step, when called:

StatementAction
1.array_splice(ind,cnt)Although the function, like splice() can have many arguments, the only first two are named: ind (the removal/insertion position) and cnt (the number of elements to be removed):
2.removeArray = this.slice(ind,ind+cnt);The elements to be removed are assigned to an array called removeArray
3.endArray = this.slice(ind+cnt);The elements after the removed ones are assigned to an array called endArray
4.this.length = ind;The array is truncated to the insertion point.
5.for(var i=2;i<arguments.length;i++){
   this[this.length] = arguments[i];
}
Any arguments other than ind or cnt passed to the function are appended to the array.
6.for(var i=0;i<endArray.length;i++){
   this[this.length] = endArray[i];
}
The elements from endArray are appended to the array.
7.return removeArray;The removed-elements-array is returned as the function exits.

As you can see the statements are based on the examples we dealt with at length earlier on. However, this is only the first draft of our prototyping function. We still have a bit of work to do.


Produced by Peter Belesis and

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

URL: https://www.webreference.com/dhtml/column33/7.html