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

如何使用JavaScript查找数组中包含特定值的所有索引

问题根因

你使用的findIndex()方法本身设计就是仅返回第一个匹配条件的元素索引,匹配到第一个符合要求的元素后就会终止遍历,所以只能拿到第一个2021对应的下标3,无法返回所有匹配结果。

解决代码

下面提供两种常用的实现方案:

方案1:reduce实现(简洁高效,一行完成逻辑)

function test() {
  const dates = [
    'October 31, 2020',
    'November 30, 2020',
    'December 31, 2020',
    'January 31, 2021',
    'February 28, 2021',
    'March 31, 2021',
  ];

  // 遍历数组,符合条件就把当前索引存入结果数组
  const indexes = dates.reduce((result, item, index) => {
    if (item.includes('2021')) result.push(index);
    return result;
  }, []);
  console.log(indexes); // 输出结果:[3, 4, 5]
}

方案2:forEach遍历实现(逻辑直观,适合新手理解)

function test() {
  const dates = [
    'October 31, 2020',
    'November 30, 2020',
    'December 31, 2020',
    'January 31, 2021',
    'February 28, 2021',
    'March 31, 2021',
  ];

  const indexes = [];
  dates.forEach((item, index) => {
    if (item.includes('2021')) {
      indexes.push(index);
    }
  })
  console.log(indexes); // 输出结果:[3, 4, 5]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:36:05