ECMAScript5为数组实例添加两方法:indexOf()和lastIndexOf()。这两个方法接受两个参数:要查找的项和(可选的)表示查找起点位置的索引。其中,indexOf()方法从数组的开头(位置0)开始向后查找,lastIndexOf()方法则从数组的末尾开始向前查找。

这两个方法都返回要查找的项在数组中的位置,或者在没有找到的情况下返回-1。在比较第一个参数与数组中的每一项时,会使用全等操作符;也就是说,要求查找的项必须严格相等(就像使用===一样)。

indexOf()和lastIndexOf()基本用法:

 <!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>indexOf()和lastIndexOf()</title>
</head>
<body>
<script>
var arry=[2,5,3,4,5,6,1];
document.write(arry.indexOf(3));
document.write("<br />");
document.write(arry.indexOf(5,2));
document.write("<br />");
document.write(arry.lastIndexOf(6));
document.write("<br />");
document.write(arry.lastIndexOf(5,3));
</script>
</body>
</html>

上述代码运行结果:

2

4

5

1

使用indexOf()和lastIndexOf()方法查找特定项在数组中的位置非常简单,支持它们的浏览器包括:IE9+、Firefox2+、Safari3+、Opera9.5+和Chrome。

为了能兼容其他版本的主流浏览器,可以按下面这样:

 <!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>indexOf()和lastIndexOf()</title>
</head> <body>
<script>
if(!(Array.prototype.indexOf)){
Array.prototype.indexOf=function(val){
for(var i=0;i<this.lenth;i++){
if(this[i]===val){
return i;
}else{
return -1;
}
} };
}
var arry=[2,5,3,4,5,6,1];
document.write(arry.indexOf(3));
document.write("<br />");
document.write(arry.indexOf(5,2));
document.write("<br />");
document.write(arry.lastIndexOf(6));
document.write("<br />");
document.write(arry.lastIndexOf(5,3));
</script>
</body>
</html>
05-11 18:12