Improving the Array class
One of my favourite things about Javascript is the way it allows you to add extra methods on to classes (or colections of objects) after they have been defined - including objects provided by Javascript itself! Here are a couple of simple improvements to the Array class that I put together today to help solve a problem:
Code:
/* Finds the index of the first occurence of item in the array, or -1 if not found */
Array.prototype.indexOf = function(item) {
for (var i = 0; i < this.length; i++) {
if (this[i] == item) {
return i;
}
}
return -1;
};
/* Returns an array of items judged 'true' by the passed in test function */
Array.prototype.filter = function(test) {
var matches = [];
for (var i = 0; i < this.length; i++) {
if (test(this[i])) {
matches[matches.length] = this[i];
}
}
return matches;
};
/* Adds an item on to the end of an array */
Array.prototype.append = function(item) {
this[this.length] = item;
};
var a = new Array();
a.append('item 1');
a.append('item 2');
itemsWith2InThem = a.filter(function(item) { return item.indexOf('2') > -1 });
// itemsWith2InThem is now an array containing 'item 2'
Has anyone else played around with this capability? Got any code snippets to share?