首页 > Web开发 > 详细

JS内置对象-Array之indexOf和lastIndexOf

时间:2019-11-02 15:57:34      阅读:82      评论:0      收藏:0      [点我收藏+]

 

indexOf()

技术分享图片

 

 1 var num = [1, 7, 2, 3, 4, 7, 9]
 2 var pos = num.indexOf(7)
 3 var pos1 = num.indexOf(7, 2)
 4 console.log(pos); // => 1
 5 console.log(pos1); // => 5
 6 
 7 //封装一个方法实现indexOf的功能
 8 function ArrayIndexOF(arr, value) {
 9   //检测value在arr中出现的位置
10   for(var i = 0; i < arr.length; i++) {
11     if(arr[i] === value) {
12       return i;
13     }
14   }
15   return -1;
16 }
17 
18 console.log(ArrayIndexOF(num, 7)); // => 1

 

lastIndexOf()

技术分享图片

 

 

1 var num = [1, 7, 2, 3, 4, 7, 9]
2 var pos = num.lastIndexOf(7)
3 var pos1 = num.lastIndexOf(7,2)
4 console.log(pos); // => 5
5 console.log(pos1); // => 1

 

JS内置对象-Array之indexOf和lastIndexOf

原文:https://www.cnblogs.com/nayek/p/11781502.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!