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

如何实现PokeApi多宝可梦名称模糊匹配筛选功能

宝可梦模糊搜索实现方案

核心思路

你当前调用的单宝可梦查询接口仅支持精确名称匹配,本身没有模糊搜索能力,因此需要调整实现逻辑:

  • 首次加载时请求全量宝可梦基础列表,缓存到本地变量中,避免重复请求
  • 用户输入搜索关键词时,直接在本地缓存的名称列表中做模糊匹配,过滤出符合要求的宝可梦
  • 匹配完成后可按需批量拉取宝可梦的详细信息

实现代码

const params = {
  headers: {
    'Content-Type': 'application/json'
  }
}

// 全局缓存全量宝可梦列表
let allPokemonList = []

// 预加载全量宝可梦基础信息,仅需要调用一次
const preloadAllPokemon = async () => {
  if (allPokemonList.length > 0) return
  try {
    // limit设置为10000可以拉取到目前所有宝可梦数据
    const response = await fetch('https://pokeapi.co/api/v2/pokemon?limit=10000', params)
    const result = await response.json()
    allPokemonList = result.results
  } catch (error) {
    console.log('预加载宝可梦列表失败', error)
  }
}

// 模糊搜索宝可梦
const fuzzySearchPokemon = async (keyword) => {
  // 首次搜索先加载全量列表
  if (allPokemonList.length === 0) {
    await preloadAllPokemon()
  }
  // 转小写实现大小写不敏感匹配
  const lowerKeyword = keyword.toLowerCase()
  // 过滤名称包含关键词的宝可梦
  const matchedPokemon = allPokemonList.filter(item => item.name.includes(lowerKeyword))
  // 如果需要返回详细信息,批量请求
  const detailList = await Promise.all(
    matchedPokemon.map(async item => {
      const res = await fetch(item.url, params)
      return res.json()
    })
  )
  return detailList
}

// 原有精确搜索方法可以保留
const searchPokemonExact = async name => {
  const url = `https://pokeapi.co/api/v2/pokemon/${name}`
  try {
    const response = await fetch(url, params);
    const result = await response.json();
    return result;
  } catch (error) {
    console.log(error)
  }
}

使用示例

// 搜索名称包含char的宝可梦
fuzzySearchPokemon('char').then(res => {
  console.log(res) // 会返回charmeleon、charizard等所有符合条件的宝可梦详情
})

注:如果不需要返回完整详情,只需要名称匹配结果,可以去掉批量拉取详情的逻辑,直接返回matchedPokemon即可,搜索响应速度会更快。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:39:02