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

如何让字符串数组实现包含关键词子串的检索?

实现字符串数组的子串包含检索

你遇到的问题根源在于:数组的includes()方法是严格匹配整个数组元素与目标值是否相等,而非检查元素内部是否包含目标子串,所以会返回false。结合ES2022兼容的语法,有以下几种简洁的实现方式:

基础判断:是否存在包含子串的元素

使用Array.prototype.some()方法,它会遍历数组,只要有一个元素满足回调条件就返回true,完美适配“是否存在”的需求:

const arr = ['service orders','service','orders'];
const keyword = 'order';
const hasMatchingItem = arr.some(str => str.includes(keyword));
console.log(hasMatchingItem); // 输出: true

进阶需求:获取所有包含子串的元素

如果需要提取所有符合条件的数组元素,改用Array.prototype.filter()即可:

const arr = ['service orders','service','orders'];
const keyword = 'order';
const matchedStrings = arr.filter(str => str.includes(keyword));
console.log(matchedStrings); // 输出: ['service orders', 'orders']

补充说明

  • 字符串的includes()方法(ES6引入,ES2022完全支持)负责检查单个字符串是否包含目标子串。
  • some()和filter()都是标准数组方法,ES2022对其完全兼容,逻辑直观且性能优异,适合绝大多数场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 11:52:07