Array Prototyping for Legacy Support

Relates to DOM Scripting and Exploder

This is a reminder to self (since this trap keeps stinging me!) that IE 5.01 does not support the principle Array object methods in Javascript. A way around this problem is to test for the presence of these methods in the Array prototype property and if they do not exist define them. Here are examples for Array.push and Array.splice which I find myself using regularly in DOM based scripts.


if (typeof Array.prototype.push == "undefined") {
  Array.prototype.push = function(str) {
    this[this.length] = str;
  }
}

if (typeof Array.prototype.splice == "undefined") {
  Array.prototype.splice = function(offset, length) {
    var temp = [];
    for (var i = this.length - 1; i >= 0; i–) {
      if (i < offset || i > (offset + length - 1)) {
        temp[temp.length] = this[i];
      }
      this.length–;
    }
    for (i = temp.length - 1; i >= 0; i–) {
      this[this.length] = temp[i];
    }
  }
}

Posted on Friday, Aug 13, 2004 at 05:07:03.

Comments on Array Prototyping for Legacy Support (2)

α comment

Please note that your CMS converted the "dashdash (i - -)" in your for-loops to an 'en dash' (–). Apart from that, it's lovely.

Posted by Menno van Slooten
Tuesday, Jun 14, 2005 at 10:32:16

β comment

Cheers for pointing that out Menno. Fixed now :)

Posted by Tom
Monday, Aug 01, 2005 at 19:41:18

Breadcrumbs Trail

[ Home ] -> TW Blog -> Aug 04 -> Array Prototyping for Legacy Support
Site Map

The Severn Solutions website achieves the following standards:

[ XHTML 1.0 ] [ CSS 2 ] [ WAI AA ] [ Bobby AA ]

Page compiled in 0.030 seconds