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>

最新文章

  1. WdatePicker 没有权限 不能执行已释放 Script 的代码
  2. ARP (地址解析协议)
  3. xcode 自定义Eclipse里边常用的快捷键
  4. Null值的使用
  5. linux文件创建、查看、编辑命令
  6. centos升级支持到C++11, gcc4.8.2
  7. Python全栈之路-----基础篇
  8. Windows无法安装到GPT分区形式磁盘的解决办法
  9. UVALive 5962 Strongly Connected Chemicals --最大独立集
  10. 使用jQuery向asp.net Mvc传递复杂json数据-ModelBinder篇
  11. Junit手动/自动加载spring配置文件
  12. junit学习(3.x)
  13. hosts文件简析
  14. SWT中的多线程(Invalid thread access)
  15. 《javascript设计模式与开发实践》阅读笔记(16)—— 状态模式
  16. Android中的线程池
  17. [六] 函数式接口的复合方法示例 predicate 谓词逻辑运算 Function接口 组合运算 比较器 逆序 比较链
  18. php笔记(一)php介绍及数据类型
  19. 设置外部查找工具来索引 Confluence 6
  20. c语言搜索子字符串

热门文章

  1. when|nobody|hazard|lane|circuit|
  2. 瑞星发布Linux系统安全报告:Linux病毒或将大面积爆发
  3. Django中查询相关操作
  4. leetcode简单题6
  5. vscode写react有warning
  6. 831. KMP字符串
  7. 当学术邂逅浪漫 – 记MobiCom 2015大会
  8. stat()函数--------------获取文件信息
  9. 错综复杂!“两桶油”与多个APP上演暧昧秀
  10. 从VR泛滥到倒闭看热门投机的山寨创业心态