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

如何在JavaScript数组中查找包含指定子串的字符串对应的序号

你当前使用的Array.find()仅会返回匹配到的元素本身,要获取对应位置序号可以使用以下两种方案:

方案1:直接使用findIndex方法(推荐)

Array.findIndex()会直接返回第一个匹配元素的0基数组索引,你需要的1起始序号直接在索引基础上加1即可:

var array = ["fox jumps", "snail slides", "airplane flies"];
// 查找匹配元素的0基索引,无匹配项时返回-1
const matchIndex = array.findIndex(item => item.includes("airplane"));
// 转换为你需要的1起始序号,无匹配时可按需返回自定义值
const result = matchIndex >= 0 ? matchIndex + 1 : "无匹配项";
console.log(result); // 输出3

方案2:基于现有匹配元素用indexOf获取索引

如果不想改动你已经写好的find逻辑,也可以用Array.indexOf获取该元素的索引:

var array = ["fox jumps", "snail slides", "airplane flies"];
var el = array.find(a =>a.includes("airplane"));
const matchIndex = array.indexOf(el);
const result = matchIndex >= 0 ? matchIndex + 1 : "无匹配项";
console.log(result); // 输出3

注意:如果数组中存在多个完全相同的元素,方案2会返回第一个出现该元素的索引,和find返回的第一个匹配元素位置一致,结果不受影响;如果需要更高查询效率优先选择方案1,仅遍历一次数组即可拿到索引。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:57:01