查找某个元素在数组中位置
indexOf()方法
arr目标数组
findWhat 要查找的内容
indexTemp 从指定索引位置开始
*/
function queryLocation(arr,findWhat,indexTemp){
if(indexTemp == undefined){
indexTemp = 0;
}
if(arr.length < 1){return;}
var indexArr = [];
function queryLR(findWhat,indexTemp){
if(arr.indexOf(findWhat,indexTemp) != -1){
indexArr.push(arr.indexOf(findWhat,indexTemp));
indexTemp++;
queryLR(findWhat,indexTemp);
}
removeDuplicates(indexArr);
}
//得到的数组去重复--arrDup为将要去重的数组
function removeDuplicates(arrDup){
if(arrDup.length <= 1){return arrDup;}
for (var i = 0; i < arrDup.length; i++) {
if(arrDup.indexOf(arrDup[i]) != i){
arrDup.splice(i,1);
i--;
}
}
return arrDup;
}
queryLR(findWhat,indexTemp);
return indexArr;
}
//测试案例
var t = [1,2,3,1,4,5,1,3,6,1,7,1];
var result = queryLocation(t,1);
console.log(result);