JavaScript删除数组中指定值的元素
/* 方法: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
}
//在数组中获取指定值的元素索引
Array.prototype.getIndexByValue= function(value)
{
var index = -1;
for (var i = 0; i < this.length; i++)
{
if (this[i] == value)
{
index = i;
break;
}
}
return index;
}
//使用举例
a = ['1','2','3','4','5'];
var dx=a.getIndexByValue("2");
a.remove(dx); //删除下标为dx的元素
/*
* 方法: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);
相关文档:
var arr=['a','b','c'];
若要删除其中的'b',有两种方法:
1.delete方法:delete arr[1]
这种方式数组长度不变,此时arr[1]变为undefined了,但是也有好处原来数组的索引也保持不变,此时要遍历数组元素可以才用
for(index in arr)& ......
JavaScript捕获窗口关闭事件
关键字: window.close事件
javascript捕获窗口关闭事件有两种方法
1.用javascript重新定义 window.onbeforeunload() 事件
在javascript里定义一个函数即可
function window.onbeforeunload() { alert("关闭窗口")}
alert()事件将会在关闭窗口前执行,你也可以用 ......
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id ......
prototype精彩资料:
"javascript之prototype" http://www.cnblogs.com/zouhaijian/archive/2009/03/29/1424592.html(很简约但清晰的讲述了prototype的用途)
"JavaScript对象模型-执行模型" http://w ......