
本文讲解如何对二维数组(数组的数组)进行子字符串搜索,解决 filter() 原生 includes() 仅支持全字匹配的问题,通过 some() + indexOf() 实现模糊查找,并兼容字符串与对象混合结构。
本文讲解如何对二维数组(数组的数组)进行子字符串搜索,解决 `filter()` 原生 `includes()` 仅支持全字匹配的问题,通过 `some()` + `indexof()` 实现模糊查找,并兼容字符串与对象混合结构。
在实际开发中(如带搜索功能的图库、卡片列表等),我们常遇到类似结构:一个外层数组包含多个子数组,每个子数组内既有字符串元素,也可能有对象(如 { text: "...", image: "..." })。当用户在搜索框输入内容(如 "goo")时,期望匹配 "goodbye" 这类包含该子串的项——但直接使用 array.includes(searchimp) 无法满足,因为它只做严格相等判断,不支持子串搜索。
正确做法是:对外层数组调用 filter(),对每个子数组调用 some() 遍历其所有元素;对每个元素,先判断类型(typeof el === 'string'),再用 el.indexOf(searchimp) > -1 判断是否包含目标子串。some() 一旦找到匹配即返回 true,触发外层 filter() 保留该子数组。
以下是优化后的完整示例代码:
const Arrays = [
[
{ text: " first ", image: "1.jpg" },
" hello", " world", " ",
],
[
{ text: " second", image: "https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png" },
" goodbye", " world", " ",
],
[
{ text: " Salut", image: "bass.jpg" },
" Ca va", " au revoir", " ",
],
];
// 模拟搜索输入(实际项目中应从 input 元素获取)
const searchimp = "goo"; // 或 document.getElementById('searchBar').value.trim()
const showArrays = Arrays.filter(array =>
array.some(el =>
typeof el === 'string' && el.includes(searchimp)
)
);
console.log(showArrays); // 输出:[[{text:" second",...}, " goodbye"," world"," "]]✅ 关键改进点说明:
- 使用
el.includes(searchimp)替代indexOf(...) > -1—— 更简洁、语义更清晰(ES6+ 支持,现代浏览器及 Node.js 环境均兼容); -
some()天然适配“是否存在任一匹配项”的逻辑,比手动for循环或find()更语义化; - 类型守卫
typeof el === 'string'避免对对象调用.includes()报错(如undefined.includes is not a function); - 若需同时搜索对象中的
text字段(例如输入"sec"也应匹配{ text: " second" }),可扩展为:
array.some(el => {
if (typeof el === 'string') return el.includes(searchimp);
if (el && typeof el === 'object' && typeof el.text === 'string') {
return el.text.includes(searchimp);
}
return false;
})⚠️ 注意事项:
- 搜索区分大小写,如需忽略大小写,统一转为小写比较:
el.toLowerCase().includes(searchimp.toLowerCase()); - 空字符串
""会被includes("")恒定返回true,建议在过滤前校验searchimp.trim() !== ""; - 性能敏感场景下,可对
searchimp做防抖(debounce),避免高频输入频繁触发重渲染。
至此,你已掌握在嵌套数组中实现高效、健壮、可扩展的子字符串模糊搜索方案。

















