i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

Sugar Arrays: Porting over JavaScript 1.6 Array methods

As of Firefox 1.5, there has been a new wide array of Array helpers that were included in JavaScript 1.6. That's all fine and great, however there isn't a single other browser on the market (as of this writing) that supports any of the new array methods (let alone JavaScript 1.6). What's a developer to do?

Add Sugar

If you're developing for todays grade A browsers, then you can count on being able to extend Array through it's prototype. But, since I have a natural love toward things that are sweet, I've already done it for you with sugar and spice.

See the complete test specification document and download sources.

I used the Crock's simple style of augmenting objects as a base to set up all my Array methods:

Class Augmentation

Function.prototype.method = function (name, fn) {

    this.prototype[name] = fn;

    return this;

};
The source includes each and all array methods that were added in JavaScript 1.6:
  • every
  • filter
  • forEach
  • map
  • some
  • indexOf
  • lastIndexOf
Here is an example of forEach method pulled from the source file:

[].forEach

Array.

    method(

        'forEach',

        function(fn, thisObj) {

            var scope = thisObj || window;

            for ( var i=0; i < this.length; ++i ) {

                fn.call(scope, this[i], i, this);

            }

        }

);

Self-Defense

As a preventative measure to safeguard against overriding existing native browser implementations (wow that was a mouthful), I added one conditional statement at the beginning of the source that checks if Array.prototype.forEach has already been defined. See below for an illustration:

conditional object check

if ( ![].forEach ) {

  // add sugar

}

The reason that I did not put a check for every other method in the implementation is that I figure if any browser hasn't added forEach, they most likely didn't add the rest. Likewise, if a browser manufacturer did implement forEach, I'm willing to put my money that they threw in the others as well.

Enjoy!

this is who i am

Hi, my name is Dustin Diaz and I'm an Engineer @ObviousCorp. Previously @Twitter, @Google, and @Yahoo, author of Strobist® Info co-author of JavaScript Design Patterns, co-creator of the Ender JavaScript Framework, a Photographer, and an amateur Mixologist. This is my website. Welcome!

On this site I write about JavaScript. You can also follow along with my open-source work on Github.

This site is optimized and works best in Microsoft Internet Explorer 6.