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

2022-01-31 00:00:00 arrays jquery javascript

我正在尝试在 JavaScript 数组中查找元素的所有实例的索引,例如Nano".

I am trying to find the index of all the instances of an element, say, "Nano", in a JavaScript array.

var Cars = ["Nano", "Volvo", "BMW", "Nano", "VW", "Nano"];

我尝试了 jQuery.inArray,或者类似地,.indexOf(),但它只给出了元素最后一个实例的索引,在这种情况下为 5.

I tried jQuery.inArray, or similarly, .indexOf(), but it only gave the index of the last instance of the element, i.e. 5 in this case.

如何为所有实例获取它?

How do I get it for all instances?

推荐答案

.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;
}

相关文章