Home >Web Front-end >JS Tutorial >Two ways to delete specified elements in an Array array in js

Two ways to delete specified elements in an Array array in js

高洛峰
高洛峰Original
2017-01-14 10:47:081412browse

Content of this section:

js deletes the specified element in the Array array

Method one,

/*
* 方法:Array.remove(dx) 通过遍历,重构数组
* 功能:删除数组元素.
* 参数:dx删除元素的下标.
*/
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 = [&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;,&#39;5&#39;];
alert("elements: "+a+"\nLength: "+a.length);
a.remove(1); //删除下标为1的元素
alert("elements: "+a+"\nLength: "+a.length);

Method two ,

/*
* 方法:Array.baoremove(dx)
* 功能:删除数组元素.
* 参数:dx删除元素的下标.
* 返回:在原数组上修改数组.
*/
Array.prototype.baoremove = function(dx)
{
  if(isNaN(dx)||dx>this.length){return false;}
  this.splice(dx,1);
}
b = [&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;,&#39;5&#39;];
alert("elements: "+b+"\nLength: "+b.length);
b.baoremove(1); //删除下标为1的元素
alert("elements: "+b+"\nLength: "+b.length);

The above two methods of js deleting specified elements in the Array array are all the content shared by the editor. I hope it can give you a reference, and I hope you will learn more. Support PHP Chinese website.

For more js methods to delete specified elements in an Array array, please pay attention to the PHP Chinese website for related articles!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn