Thursday, November 18, 2010

Extending the javascript Array object

The ubiquitous javascript Array object. We use it every day, but unfortunately it is missing a few useful things like simple get() and contains() methods. But luckily for us, its easy to extend. Here are a couple simple examples of how to extend the Array object with methods we wish it had by default.

Get Method
Create a simple array of name/value pairs.
Get an array member based on its name.

Array.prototype.get = function(key) {
var i = this.length;
while (i--) { if (this[i].split(":")[0]==key){return this[i].split(":")[1];} }

function testGetMethod() {
var opts=["1:one","2:two","3:three","4:four","5:five"];
var item = opts.get("3");
//output: three

Contains method
Create a simple array, and see if an item exists in the array.

Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) { if (this[i] === obj){return true;} }
return false;

function testContainsMethod() {
var opts=[1,2,3,4,5,10];
//output: true

Just include the "Array.prototype..." methods somewhere in your page, or a global .js file to make them available to all your pages.