且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何找到数组中所有出现元素的索引?

更新时间:2023-02-18 09:53:54

.indexOf() 方法 有一个可选的第二个参数,用于指定开始搜索的索引,因此您可以在循环中调用它以查找一个特定的值:

The .indexOf() method has an optional second parameter that specifies the index to start searching from, so you can call it in a loop to find all instances of a particular value:

function getAllIndexes(arr, val) {
    var indexes = [], i = -1;
    while ((i = arr.indexOf(val, i+1)) != -1){
        indexes.push(i);
    }
    return indexes;
}

var indexes = getAllIndexes(Cars, "Nano");

您并没有明确说明您想如何使用索引,因此我的函数将它们作为数组返回(如果找不到该值,则返回一个空数组),但是您可以使用循环内的各个索引值.

You don't really make it clear how you want to use the indexes, so my function returns them as an array (or returns an empty array if the value isn't found), but you could do something else with the individual index values inside the loop.

更新:根据 VisioN 的评论,简单的 for 循环可以更有效地完成相同的工作,并且更易于理解,因此更易于维护:

UPDATE: As per VisioN's comment, a simple for loop would get the same job done more efficiently, and it is easier to understand and therefore easier to maintain:

function getAllIndexes(arr, val) {
    var indexes = [], i;
    for(i = 0; i < arr.length; i++)
        if (arr[i] === val)
            indexes.push(i);
    return indexes;
}