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

如何在含对象的JavaScript数组中根据子串查找元素索引?

查找数组中包含指定子串的元素索引

先明确需求:从给定的对象数组里,找出message字段包含指定子串的元素索引,最终返回索引数组。

给定的数组和目标子串:

const data = [
  {message:'hello there my name is'},
  {message:'this is a test'}
];
const toFind = 'hello there';

分享两种实用实现方式,刚好能用到你提到的includes()或indexOf():

方法1:forEach循环手动收集索引

const resultIndexes = [];

data.forEach((item, index) => {
  // 用includes判断是否包含子串,符合条件就存入索引
  if (item.message.includes(toFind)) {
    resultIndexes.push(index);
  }
});

console.log(resultIndexes); // 输出 [0]

如果想用indexOf()替代,把判断条件换成item.message.indexOf(toFind) !== -1即可——indexOf()找不到子串会返回-1,只要结果不为-1就说明包含目标内容。

方法2:用reduce简化代码逻辑

const resultIndexes = data.reduce((acc, item, index) => {
  item.message.includes(toFind) && acc.push(index);
  return acc;
}, []);

console.log(resultIndexes); // 输出 [0]

reduce可以在遍历数组的同时直接累积结果,初始值设为空数组,每次检查符合条件就把索引加入数组,最后返回这个累积好的结果数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:44:59