[英]Gettng the indexes of items and putting the indexes in a different array
我特別想知道為什么這個解決方案不起作用。
您應該創建一個函數,該函數返回數組中所有出現項的索引。
給定數組 ['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] 這是為什么?
而不是這個,使用:
for(var i=0;i<arr.length;i++) {
if (arr[i] === el) {
a.push(i);
}
}
正如@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)
嘗試這個:
arr = ['a', 'a', 'b', 'a', 'b', 'a']
el = 'a'
a = []
arr.forEach(function (value,i){
if (value === el) a.push(i);
});
利用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"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.