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

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

问题描述

我试图找到所有的元素,比方说,纳米,在JavaScript数组中。

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 ,或类似,<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf\"相对=nofollow>。的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?

推荐答案

的<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf\"><$c$c>.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天全站免登陆