我想在没有方法的情况下在相同的数组中找到元素 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);
}
}
答案 0 :(得分:5)
要获得所有职位,你必须在返回之前走完整个数组
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]
答案 1 :(得分:0)
我建议:
count (haystack, needle) {
return haystack.filter(function (el, index) {
if (el === needle) {
return index;
}
});
}