js Deletes an instance of an array by specifying a subscript or specifying an element

  • 2021-07-10 18:28:13
  • OfStack

Examples are as follows:


 Deletes the specified subscript array element  
Array.prototype.del=function(index){ 
    if(isNaN(index)||index>=this.length){ 
      return false; 
    } 
    for(var i=0,n=0;i<this.length;i++){ 
      if(this[i]!=this[index]){ 
        this[n++]=this[i]; 
      } 
    } 
    this.length-=1; 
  }; 
 Delete the specified element  
 
    Array.prototype.indexOf = function(val) { 
      for (var i = 0; i < this.length; i++) { 
        if (this[i] == val) return i; 
      } 
      return -1; 
    }; 
    Array.prototype.remove = function(val) { 
      var index = this.indexOf(val); 
      if (index > -1) { 
        this.splice(index, 1); 
      } 
    }; 
    function a(){ 
      var arr = [1, 2, 3, 4, 5]; 
    alert(arr.toString()); 
    arr.remove(3); 
    alert(arr.toString()); 
    } 

The first calling mode

arr.del(0);


Related articles: