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相关问答推荐

在shiny 的datatable列中启用智能搜索

在范围内设置文本

Facebook 风格的 JQuery 自动完成插件

JQuery 仅在 Rails 4 应用程序中的页面刷新时加载

如何在jQuery中 Select 具有特定ID的所有元素?

jQuery JSON到字符串?

jQuery UI 滑块(以编程方式设置)

字符串化(转换为 JSON)具有循环引用的 JavaScript 对象

jquery beforeunload 关闭(不离开)页面时?

使用 jQuery 从 AJAX 响应(json)构建表行

jQuery Button.click() 事件被触发两次

jQuery:如何从 $.ajax.error 方法中获取 HTTP 状态代码?

你如何在Javascript中缓存图像

jQuery 按值 Select 选项元素

在ajax请求中检测重定向?

如何使用 jQuery 取消设置元素的 CSS 属性?

设置 JQuery event.preventDefault() 时绕过 window.open 上的弹出窗口阻止程序

默认情况下如何将tinymce粘贴为纯文本

在 Firefox 上开发的 Javascript 在 IE 上失败的典型原因是什么?

JS - 从base64代码中获取图片的宽高