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

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 删除数组元素.


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-10   浏览: 408 ::
收藏到网摘: 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>