如何找到数组中所有出现元素的索引? [英] How to find index of all occurrences of element in array?

查看:31
本文介绍了如何找到数组中所有出现元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 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;
}

这篇关于如何找到数组中所有出现元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆