当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JavaScript学习:删除数组元素

Javascript
JavaScript中的Navigator浏览器对象
JavaScript中的Screen屏幕对象
JavaScript中的Window窗口对象
JavaScript中的History历史对象
JavaScript中的Location地址对象
JavaScript中的Document文档对象
JavaScript中的事件处理
JavaScript中的对象化编程
JavaScript框架编程
JavaScript的Cookies
JavaScript表单常用验证集合
javascript 实现的多浏览器支持的贪吃蛇webgame
表现、结构、行为分离的选项卡效果
用JavaScript 判断用户使用的是 IE6 还是 IE7
msn上的tab功能Firefox对childNodes处理的一个BUG
jquery 插件 人性化的消息显示
零基础学JavaScript最新动画教程+iso光盘下载
用jQuery实现检测浏览器及版本的脚本代码
在Javascript类中使用setTimeout
Javascript 写的简单进度条控件

Javascript 中的 JavaScript学习:删除数组元素


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-10   浏览: 544 ::
收藏到网摘: n/a

JavaScript通过设置数组的length属性来截断数组是惟一一种缩短数组长度的方法.如果使用delete运算符来删除数组中元素,虽然那个元素变成未定义的,但是数组的length属性并不改变两种删除元素,数组长度也改变的方法.


<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+"\nLength: "+a.length);
a.remove(0); //删除下标为0的元素
alert("elements: "+a+"\nLength: "+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+"\nLength: "+b.length);
b.baoremove(1); //删除下标为1的元素
alert("elements: "+b+"\nLength: "+b.length);
</script>