我想在同一个数组中找到一个元素的POSITIONS,没有方法,有一个算法...
示例:
var a = [1,2,2,1,4,5,6]
to display positions of 1 : position 0 and 3
to display positions of 2 : position 1 and 2
到目前为止我做了什么:
function count(array,element){
while(element in array){
return array.indexOf(element);
}
}
最佳答案
为了得到所有的位置,你必须在返回之前遍历整个数组
var a = [1,2,2,1,4,5,6]
function count(array,element){
var counts = [];
for (i = 0; i < array.length; i++){
if (array[i] === element) {
counts.push(i);
}
}
return counts;
}
count(a, 1); //returns [0,3]
count(a, 2); //returns [1,2]
关于javascript - 多次查找数组中相同元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27443170/