一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

示例:js查找数组中指定元素并返回该元素的所有索引

时间:2017-04-02 编辑:简简单单 来源:一聚教程网

示例代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

//在数组中查找所有出现的x,并返回一个包含匹配索引的数组

functionfindall(a,x){

 varresults=[],

   len=a.length,

   pos=0;

 while(pos

  pos=a.indexOf(x,pos);

  if(pos===-1){//未找到就退出循环完成搜索

   break;

  }

  results.push(pos);//找到就存储索引

  pos+=1;//并从下个位置开始搜索

 }

 returnresults;

}

  

vararr=[1,2,3,1,4,1,4,1];

findall(arr,1);//返回[0,3,5,7]

热门栏目