JavaScript通過(guò)設(shè)置數(shù)組的length屬性來(lái)截?cái)鄶?shù)組是惟一一種縮短數(shù)組長(zhǎng)度的方法.如果使用delete運(yùn)算符來(lái)刪除數(shù)組中元素,雖然那個(gè)元素變成未定義的,但是數(shù)組的length屬性并不改變兩種刪除元素,數(shù)組長(zhǎng)度也改變的方法.
<script>
/*
* 方法:Array.remove(dx)
* 功能:刪除數(shù)組元素.
* 參數(shù):dx刪除元素的下標(biāo).
* 返回:在原數(shù)組上修改數(shù)組
*/
//經(jīng)常用的是通過(guò)遍歷,重構(gòu)數(shù)組.
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); //刪除下標(biāo)為0的元素
alert("elements: "+a+"\nLength: "+a.length);
/*
* 方法:Array.baoremove(dx)
* 功能:刪除數(shù)組元素.
* 參數(shù):dx刪除元素的下標(biāo).
* 返回:在原數(shù)組上修改數(shù)組.
*/
//我們也可以用splice來(lái)實(shí)現(xiàn).
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); //刪除下標(biāo)為1的元素
alert("elements: "+b+"\nLength: "+b.length);
</script>
聯(lián)系客服