如何在含对象的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
相关产品推荐
相关产品推荐

