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
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 ifArray.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!
recent
- Matador: The Obvious MVC Framework for Node
- Sandboxing JavaScript
- Crouching Ender, hidden command
- Ender.js - The open submodule library
- Qwery - The Tiny Selector Engine
- Klass
- Smallest DOMReady code, ever.
- $script.js - Another JavaScript loader
- About that slowness on Twitter...
- Autocomplete Fuzzy Matching
- JavaScript Cache Provider
- JavaScript Animate
- Asynchronous method queue chaining in JavaScript
- Something changed
- Unofficial Twitter Widget Documentation
i am dustin diaz

