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

JavaScript中使用find方法如何获取所有匹配项而非仅首个结果?

问题原因
  • Array.find() 方法的设计逻辑是仅返回数组中第一个满足测试条件的元素,找到第一个匹配项后就会停止遍历,因此只会返回第二个包含red的字幕块。
  • 原代码存在变量名书写错误:定义的字符串变量名为string,调用split方法时误用了不存在的变量st。
修复方案

将find方法替换为Array.filter()即可,filter会遍历完整数组,返回所有满足条件的元素组成的新数组。

修复后的完整代码:

const string = `1
00:01:46,356 --> 00:01:49,893
test test test test

2
00:01:50,794 --> 00:01:54,998
test test test red test test

3
00:01:55,199 --> 00:01:58,267
test test red`;

// 替换find为filter,同时修正变量名错误
const matches = string.split('\n\n').filter((e) => e.includes('red'));

console.log(matches);

运行后matches会输出包含两个符合条件的字幕块的数组,可直接遍历使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:15:10