//在數組中查找所有出現的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]
