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

如何在JavaScript数组中查找包含指定单词的元素?

解决方法:根据关键词筛选数组元素

嘿,这个需求在日常开发里太常见啦!用JavaScript的数组原生方法就能轻松搞定,我给你一步步拆解:

基础实现(精确匹配大小写)

首先,我们可以用Array.filter()结合字符串的includes()方法,筛选出name属性包含指定关键词的元素:

// 定义你的联系人数组
const contacts = [
  {name: "Jeff Crawford", tel: "57285"},
  {name: "Jeff Maier", tel: "52141"},
  {name: "Tim Maier", tel: "73246"}
];

// 编写搜索函数
function searchContacts(keyword) {
  // filter会遍历数组,返回所有满足条件的元素
  return contacts.filter(contact => contact.name.includes(keyword));
}

// 测试搜索"Jeff"
const result = searchContacts("Jeff");
console.log(result);
// 输出:[{name: "Jeff Crawford", tel: "57285"}, {name: "Jeff Maier", tel: "52141"}]

优化:忽略大小写的搜索

如果希望搜索时不区分大小写(比如输入"jeff"也能匹配到),可以把关键词和目标字符串都转成小写后再判断:

function searchContacts(keyword) {
  const lowerCaseKeyword = keyword.toLowerCase();
  return contacts.filter(contact => 
    contact.name.toLowerCase().includes(lowerCaseKeyword)
  );
}

// 测试小写关键词
const result = searchContacts("jeff");
console.log(result);
// 同样会返回正确的两个元素

进阶:严格匹配开头

如果你需要的是名字以关键词开头的元素(而不是任意位置包含),可以把includes()换成startsWith():

function searchContacts(keyword) {
  return contacts.filter(contact => contact.name.startsWith(keyword));
}

同样,忽略大小写的版本也可以这么写:

function searchContacts(keyword) {
  const lowerCaseKeyword = keyword.toLowerCase();
  return contacts.filter(contact => 
    contact.name.toLowerCase().startsWith(lowerCaseKeyword)
  );
}

这些方法都很灵活,你可以根据自己的实际需求来选择~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:30:30