You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取JavaScript数组中相同元素的所有索引?

获取数组中同一元素的所有索引

先看你提供的示例代码:

const fruits = ["Banana", "Orange", "Apple", "Mango","Apple"];
console.log(fruits.indexOf("Apple") ); // 输出2

要获取目标元素的所有索引,有几种实用的实现方式:

方法一:使用forEach遍历收集

遍历数组的每个元素,当元素匹配目标值时,将对应的索引存入结果数组:

const fruits = ["Banana", "Orange", "Apple", "Mango","Apple"];
const target = "Apple";
const indices = [];

fruits.forEach((item, index) => {
  if (item === target) {
    indices.push(index);
  }
});

console.log(indices); // [2, 4]

方法二:使用reduce简化写法

利用reduce的累加器特性,一步完成索引收集:

const fruits = ["Banana", "Orange", "Apple", "Mango","Apple"];
const target = "Apple";
const indices = fruits.reduce((acc, item, index) => {
  return item === target ? [...acc, index] : acc;
}, []);

console.log(indices); // [2, 4]

方法三:结合indexOf循环查找

利用indexOf的第二个参数(指定搜索起始位置),循环查找直到找不到目标元素为止:

const fruits = ["Banana", "Orange", "Apple", "Mango","Apple"];
const target = "Apple";
const indices = [];
let currentPos = fruits.indexOf(target);

while (currentPos !== -1) {
  indices.push(currentPos);
  currentPos = fruits.indexOf(target, currentPos + 1);
}

console.log(indices); // [2, 4]

这几种方法都能满足需求,你可以根据代码风格和实际场景选择合适的方式。

内容的提问来源于stack exchange,提问作者jessica smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:37:12