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

如何在JavaScript中搜索数组文本并获取匹配元素的索引

问题分析

你当前的代码逻辑存在缺陷:调用filter生成过滤后的新数组后,后续forEach遍历拿到的index是新数组的下标,并非元素在原数组中的原始索引,因此输出结果不符合需求。以你给出的示例为例,匹配ma的元素是原数组下标为1的mango和下标为3的banana,现有代码只会输出[0,1],无法拿到正确原索引。


正确实现方案

方案1:直接遍历原数组收集索引(最易理解)

const arr = ['apple', 'mango', 'orange', 'banana'];

const customFilter = (arr, searchtxt) => {
  const result = [];
  // 直接遍历原数组,拿到的i就是原始索引
  arr.forEach((fruit, i) => {
    if (fruit.match(searchtxt)) {
      result.push(i);
    }
  })
  return result;
}

console.log(customFilter(arr, 'ma')); // 输出 [1, 3],符合预期

方案2:reduce简化写法(代码更简洁)

const customFilter = (arr, searchtxt) => {
  return arr.reduce((res, fruit, index) => {
    fruit.match(searchtxt) && res.push(index);
    return res;
  }, [])
}

优化提示

如果只是做简单的字符串包含校验,推荐用fruit.includes(searchtxt)替代fruit.match(searchtxt),性能更好,也不会出现正则匹配的意外问题。

如果需要同时拿到匹配元素和对应原索引,可以调整返回结构:

const customFilter = (arr, searchtxt) => {
  return arr.reduce((res, fruit, index) => {
    if (fruit.match(searchtxt)) {
      res.push({ index, element: fruit });
    }
    return res;
  }, [])
}
// 输出 [{index:1, element:'mango'}, {index:3, element:'banana'}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:54:07