js Two Ways to Delete Specified Elements from Array Array
- 2021-07-07 06:29:25
- OfStack
Contents of this section:
js Deletes the specified element from the Array array
Method 1,
/*
* Method :Array.remove(dx) By traversing , Reconstruct array
* Function : Delete Array Elements .
* Parameter :dx Delete the subscript of an element .
*/
Array.prototype.remove=function(dx)
{
if(isNaN(dx)||dx>this.length){return false;}
for(var i=0,n=0;i<this.length;i++)
{
if(this[i]!=this[dx])
{
this[n++]=this[i]
}
}
this.length-=1
}
a = ['1','2','3','4','5'];
alert("elements: "+a+"\nLength: "+a.length);
a.remove(1); // Delete subscript as 1 Elements of
alert("elements: "+a+"\nLength: "+a.length);
Method 2,
/*
* Method :Array.baoremove(dx)
* Function : Delete Array Elements .
* Parameter :dx Delete the subscript of an element .
* Return : Modify the array on the original array .
*/
Array.prototype.baoremove = function(dx)
{
if(isNaN(dx)||dx>this.length){return false;}
this.splice(dx,1);
}
b = ['1','2','3','4','5'];
alert("elements: "+b+"\nLength: "+b.length);
b.baoremove(1); // Delete subscript as 1 Elements of
alert("elements: "+b+"\nLength: "+b.length);