Friday, November 30, 2007

Static methods for Array

I wrote today a small piece of code, to add static methods to Array. These methods allow developers to manipulate arrays, arguments, node collections and array-like hashes in a normalized way. Using the built-in methods that arrays have. The js won't add forEach, map, etc. It will only take, those methods available for arrays, will make them compatible for array-like objects, and will append them to the Array object.

Extending the prototype of native object is a bad practice (for many) and will pollute the global scope (I fully agree with this). The added functions, will be only fulfilling the lack of these methods, in browsers that don't support them( only Firefox supports them, that I know of ).

Array static methods in Firefox, don't support node collections though. So calling this:

Array.pop(document.getElementsByTagName('p'));
Will fail in Firefox. Using:
[].pop.apply(document.getElementsByTagName('p'));
Won't work for nodes, and will throw an error in any browser.

That's why there're two versions of this code. The one called array, and array.lite. The latter won't override existing methods. In consequence, node collections won't be supported. On the contrary, array, will override as much as possible, ensuring support for node collections for those methods found in the prototype.

Here's a small demo to show it's use. It has been tested on Windows XP in IE6, FF 2, Safari 3 and Opera 9.22. I'm not sure, but it seems to be a little buggy in Opera, I still haven't figured out why.

Links Downloads: If this code is added after normalizing the new iteration methods they will also be added to the Array object

0 comments: