Recetas Código: Javascript

De Daniel Pecos

Contenido

Ordenación de un array

    Array.prototype.sort = function()
    {
       var tmp;
       for(var i=0;i<this.length;i++)
       {
           for(var j=0;j<this.length;j++)
           {
               if(this[i]<this[j])
               {
                   tmp = this[i];
                   this[i] = this[j];
                   this[j] = tmp;
               }
           }
       }
    };

Desplazamiento de los elementos de un array una posición hacia la derecha

    Array.prototype.unshift = function(item)
    {
       this[this.length] = null;/* create a new last element */
       for(var i=1;i<this.length;i++)
       {
           this[i] = this[i-1]; /* shift elements upwards */
       }
       this[0] = item;
    };

Desplazamiento de los elementos de un array una posición hacia la izquierda

    Array.prototype.shift = function()
    {
       for(var i=1;i<this.length;i++) {
           this[i-1] = this[i] /* shift element downwards */
       }
       this.length =  this.length-1;
    };

Vaciar un array

    Array.prototype.clear = function()
    {
       this.length = 0;
    };

Comprobar si un elemento está contenido en un array

    Array.prototype.contains = function (element)
    {
       for (var i = 0; i < this.length; i++) {
          if (this[i] == element)
             return true;
       }
       return false;
    };

Reordenar de forma aleatoria un array

    Array.prototype.shuffle = function() 
    {     
       var i=this.length,j,t;     
       while(i--) {         
          j=Math.floor((i+1)*Math.random());         
          t=arr[i];         
          arr[i]=arr[j];         
          arr[j]=t;     
       } 
    };

Eliminar elementos duplicados en un array

    Array.prototype.unique = function()
    {     
       var a=[],i;     
       this.sort();     
       for(i=0; i<this.length; i++) {         
          if(!a.contains(this[i]))
             a[a.length] = this[i];         
       }     
       return a; 
    };

Devolver la última posición de un elemento dentro de un array

    Array.prototype.lastIndexOf = function(n)
    {     
       var i=this.length;     
       while(i--) {         
          if(this[i]===n)           
             return i;         
       }     
       return -1; 
    };
Herramientas personales