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

如何优化JavaScript数组中匹配子串的索引提取代码?

优化方案分析

你的代码功能正常,但可以从变量声明、语义化、性能几个维度优化,下面是几种更优的实现方式:

原代码的可改进点

  • 变量tv_show和indexesFromSearch未用const/let声明,会成为全局变量,存在污染风险
  • forEach中直接用参数elem即可,无需通过tv_show[index]重复取值
  • substring(0,5)可以用语义更清晰的startsWith("bbc1_")替代,不用硬编码子串长度
  • forEach中的return indexesFromSearch无效,因为forEach不会处理回调的返回值

优化实现方式

1. 使用reduce(一次遍历,性能最优)

reduce可以在单次遍历中完成筛选和收集,是效率最高的方式:

const tv_show = ["bbc1_7.30","bbc1_8.00","itv1_8.40","bbc1_10.00"];
const indexesFromSearch = tv_show.reduce((resultList, currentItem, currentIndex) => {
  if (currentItem.startsWith("bbc1_")) {
    resultList.push(currentIndex);
  }
  return resultList;
}, []);

alert(indexesFromSearch);

2. 使用map + filter(可读性强,逻辑清晰)

先通过map把符合条件的索引映射出来,再用filter过滤掉无效值,逻辑更直观:

const tv_show = ["bbc1_7.30","bbc1_8.00","itv1_8.40","bbc1_10.00"];
const indexesFromSearch = tv_show
  .map((item, index) => item.startsWith("bbc1_") ? index : null)
  .filter(index => index !== null);

alert(indexesFromSearch);

3. 使用for...of + entries()(语法简洁,易理解)

如果习惯传统循环写法,entries()可以同时获取索引和元素,代码更简洁:

const tv_show = ["bbc1_7.30","bbc1_8.00","itv1_8.40","bbc1_10.00"];
const indexesFromSearch = [];

for (const [index, item] of tv_show.entries()) {
  if (item.startsWith("bbc1_")) {
    indexesFromSearch.push(index);
  }
}

alert(indexesFromSearch);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:33:31