How to find index of all occurrences of element in array?(如何查找数组中所有出现的元素的索引?)
问题描述
我正在尝试在 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;
}
这篇关于如何查找数组中所有出现的元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何查找数组中所有出现的元素的索引?


- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01