<script language="javascript1.5" type="text/javascript">
/*自定义一个函数,实现删除数组中几项的功能*/
function delCon(argAry,bgnIndex,delNumber){
if(argAry==null||argAry.length==0) return "";
var len=argAry.length;
if(bgnIndex>len) return "";
//此处可以添加一条语句来判断参数的长度
var temAry=new Array();
for(var i=0;i<bgnIndex;i++){
temAry[i]=argAry[i];
}
for(var i=bgnIndex+delNumber;i<len;i++){
temAry[temAry.length]=argAry[i];
}
return temAry;
}
/*此函数用来获取一个数组*/
function getAry(){
var nameAry=new Array();
nameAry[0]="tom";
nameAry[1]="jhon";
nameAry[2]="jack";
nameAry[3]="rose";
nameAry[4]="angle";
nameAry[5]="glass";
nameAry[6]="halun";
return nameAry;
}
var tAry=getAry();
document.write("<span>the prototype of array is: </span>"+tAry+"<hr>");
//window.alert(ttAry);
//可以使用另外的一种方式,此处需要注意不能遗漏getAry后的括号
//数组删除第一种方式
//删除数组的任意位置可以调用delete(n)
delete tAry[1];
document.write("<span>after delete the array is: </span>"+tAry+"<hr>"+"<span>the length of array is</span>");
//删除数组的第二种方式,调用pop()、unshift()、
tAry.pop();
document.write("<span> after pop() the array is: </span>"+tAry+"<hr>");
tAry.shift();
document.write("<span> after shift() the array is :</span>"+tAry+"<hr>");
//删除数组第三种方式是将要删除的元素赋值为NULL<br>
tAry[1]=null;
document.write("<span> after assignment the array is :</span>"+tAry+"<hr>");
//删除数组的第四种方法是自己添加一个函数
document.write("<span> after design by myself the array is :</span>"+delCon(getAry(),1,1)+"<hr>");
//删除数组的第五个方法调用splice()方法
tAry.splice(1,1);
document.write("<span> after splice the array is :</span>"+tAry+"<hr>");
//var ttAry=delCon(tAry,1,1);
/*/通过调用函数delCon来实现自定义函数*/
//删除数组的
function delLast(argAry)
{
return delCon(argAry,argAry.length-1,1);
}
//window.alert(delLast(tAry));
//调用数组的自带函数pop删除数组的最后一项
//push函数的返回值是删除的那个元素,应该是先调用pop函数,然后输出数组
tAry.pop();
document.write(tAry+"<hr>");
</script>
JavaScript数组删除项的方法
最新推荐文章于 2024-01-11 11:42:42 发布