繁体   English   中英

获取项目的索引并将索引放在不同的数组中

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM