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

如何在JavaScript中使用indexOf()查找所有匹配项的索引

查找数组中所有匹配项的索引方法

针对你给出的数组,这里提供几种实用的方法来获取所有匹配元素的索引:

方法一:利用indexOf()循环查找

indexOf()支持第二个参数指定起始搜索位置,我们可以通过循环不断更新起始位置,直到找不到匹配项为止:

const fruits = ["apple", "orange", "banana", "apple", "grape", "apple"];
const target = "apple";
const indices = [];
let currentIndex = fruits.indexOf(target);

while (currentIndex !== -1) {
  indices.push(currentIndex);
  // 从当前索引的下一位开始继续搜索,避免重复匹配
  currentIndex = fruits.indexOf(target, currentIndex + 1);
}

console.log(indices); // 输出 [0, 3, 5]

方法二:用forEach()遍历记录索引

直接遍历数组的每个元素,判断是否匹配目标值,匹配则记录对应的索引:

const fruits = ["apple", "orange", "banana", "apple", "grape", "apple"];
const target = "apple";
const indices = [];

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

console.log(indices); // 输出 [0, 3, 5]

方法三:使用reduce()累积结果

通过reduce()方法遍历数组,将符合条件的索引累积到结果数组中:

const fruits = ["apple", "orange", "banana", "apple", "grape", "apple"];
const target = "apple";

const indices = fruits.reduce((acc, fruit, index) => {
  if (fruit === target) {
    acc.push(index);
  }
  return acc;
}, []);

console.log(indices); // 输出 [0, 3, 5]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:24:27