js-数组中查找特定元素并返回所有该元素的索引

//在数组中查找所有出现的x,并返回一个包含匹配索引的数组
function findall(a,x){
  var results=[],
      len=a.length,
      pos=0;
  while(pos<len){
    pos=a.indexOf(x,pos);
    if(pos===-1){//未找到就退出循环完成搜索
      break;
    }
    results.push(pos);//找到就存储索引
    pos+=1;//并从下个位置开始搜索
  }
  return results;
}

var arr=[1,2,3,1,4,1,4,1];
findall(arr,1);//返回[0,3,5,7]
原文地址:https://www.cnblogs.com/zczhangcui/p/6268901.html