Extendiendo el objeto Array

Una de las mejores características de javascript es que se pueden añadir funciones a las 'clases' en cualquier momento a traves de la propiedad prototype.
Aprovechando esta capacidad podemos extender el objeto Array para añadirle funcionalidades de búsqueda y eliminación.

array.indexOf
Devuelve el indice del array en el que se encuentra el elemento. Devuelve -1 si no encuentra el elemento

  1. Array.prototype.indexOf = function(element) {
  2.   for (var i = 0; i <this.length; i++) {
  3.     if(this[i] == element) return i;
  4.   }
  5.   return -1;
  6. };


array.exists

Devuelve true si el elemento se encuentra en el array, haciendo uso de la funcion indexOf

  1. Array.prototype.exists = function(element) {
  2.   return this.indoexOf(element) != -1;
  3. };

array.filter
Devuelve un array que contiene solo los elementos para los que la función pasada como argumento devuelve true

  1. Array.prototype.filter = function(fn) {
  2.   var array = [];
  3.   for (var i = 0; i <this.length; i++) if(fn(this[i])) array.push(this[i]);
  4.   return array;
  5. };

array.removeIndex
Elimina todos los elementos del array que están entre los índices from y to. Si solo se especifica valor para from, se elimina solo el elemento que se encuentra en ese índice.

  1. Array.prototype.removeIndex = function(from, to) {
  2.   if (from <0) return;
  3.   var rest = this.slice((to || from) + 1 || this.length);
  4.   this.length = from <0 ? this.length + from : from;
  5.   return this.push.apply(this, rest);
  6. };

array.remove
Elimina un elemento del array, usando las funciones removeIndex e indexOf

  1. Array.prototype.remove = function(e) {
  2.   return this.removeIndex(this.indexOf(e));
  3. };

array.execute
Ejecuta la función fn pasandole como argumento cada elemento del array
si le pasamos el argument obj, se ejecutara la funcion fn como si perteneciese al objeto obj

  1. Array.prototype.execute = function(fn, owner) {
  2.   for (var i=0; i<;this.length; i++){
  3.     if (owner) fn.call(owner, this[i]);
  4.     else if (typeof this[i] != 'function') fn(this[i]);
  5.   }
  6. }

array.foreach
Ejecuta la función fn en cada elemento del array, pasandole como argumentos los elementos contenidos en el array args
si le pasamos el argument obj, se ejecutara la funcion fn como si perteneciese al objeto obj

  1. Array.prototype.foreach = function(fn, args) {
  2.   for (var i=0; i<this.length; i++) {
  3.     fn.apply(this[i], args);
  4.   }
  5. }

Share:
  • del.icio.us
  • Google
  • E-mail this story to a friend!
  • Print this article!

Leave a Comment