我特别想知道为什么此解决方案不起作用。
您应该创建一个函数,该函数返回数组中某项所有出现的索引。
给出数组['a','a','b','a','b','a']
我想找到元素'a'的所有索引,并将其放在另一个数组中
我知道有不同的方法可以做到这一点,但是我做到了
function getIndices(arr, el) {
a = [];
for(i of arr){
if(i === el) a.push(Number(arr.indexOf(i)));
}
return a;
}
但是当我运行它时,返回的全部是[0,0,0,0] 为什么会这样?
答案 0 :(得分:0)
请使用:
for(var i=0;i<arr.length;i++) {
if (arr[i] === el) {
a.push(i);
}
}
答案 1 :(得分:0)
正如@reikyoushin和@Barmer在评论中提到的,indexOf
返回第一个元素的索引。
一个更好的解决方案是尝试以下方法:
function indexOfElement(value, index, array) {
if(value === this.searchElement)
return index;
}
const inputArray = [1, 4, 7, 22, 2, 7, 7, 3];
const indices = inputArray
.map(indexOfElement, { searchElement: 7 })
.filter((e) => e !== undefined)
答案 2 :(得分:0)
尝试一下:
arr = ['a', 'a', 'b', 'a', 'b', 'a']
el = 'a'
a = []
arr.forEach(function (value,i){
if (value === el) a.push(i);
});
答案 3 :(得分:0)
使用indexOf
第二个参数fromIndex
。
这是经过修改的代码。
function getIndices(arr, el) {
a = [];
let last = -1;
for (i of arr) {
if (i === el) a.push(Number(last = arr.indexOf(i, last+1)));
}
return a;
}
const data = ["a", "a", "b", "a", "b", "a"];
console.log(getIndices(data, "a"));
或者使用reduce
const getIndices2 = (arr, el) =>
arr.reduce((acc, cur, i) => {
if (cur === el) acc.push(i);
return acc;
}, []);
const data = ["a", "a", "b", "a", "b", "a"];
console.log(getIndices2(data, "a"));