时间:2021-07-01 10:21:17 帮助过:17人阅读
<script>
/*
* 方法: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 = [1,2,3,4,5];
alert("elements: "+a+" Length: "+a.length);
a.remove(0); //删除下标为0的元素
alert("elements: "+a+" Length: "+a.length);
/*
* 方法:Array.baoremove(dx)
* 功能:删除数组元素.
* 参数:dx删除元素的下标.
* 返回:在原数组上修改数组.
*/
//我们也可以用splice来实现.
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+" Length: "+b.length);
b.baoremove(1); //删除下标为1的元素
alert("elements: "+b+" Length: "+b.length);
</script>