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"];

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() method有一个可选的第二个参数,该参数指定开始搜索的索引,因此您可以在循环中调用它来查找特定值的所有实例:

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.

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

Jquery相关问答推荐

如何在jQuery中判断粘贴剪贴板中字母输入的增加/减少

JQuery - 从先前选择的下拉列表中隐藏/显示选项

DataTables:无法读取未定义的属性“长度”

Bootstrap 4 多选下拉菜单

Google Maps API v3 infowindow 关闭事件/回调?

JQuery:如果 div 可见

data.map 不是函数

未捕获的 TypeError:data.push 不是函数

用于活动选项卡更改的 Bootstrap 3 jquery 事件

JavaScript 中的简单节流阀

Twitter Bootstrap css 类的 jQuery show() 隐藏

由于 MIME 类型错误,Chrome 拒绝执行 AJAX 脚本

调用 e.preventDefault() 后提交表单

将十六进制转换为 RGBA

具有动态大小图像的马赛克网格画廊

将带有数字键的 JavaScript 对象转换为数组

jQuery select2 获取选择标签的值?

修改查询字符串而不重新加载页面

jQuery - 使用发布数据重定向

等效于 C# LINQ Select 的 Javascript