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

使用Pokemon API构建JS随机宝可梦生成器,如何正确获取属性类型?

解决Pokemon API宝可梦类型提取问题

你遇到的问题是因为pokemon.types是对象数组,直接赋值会将对象转为默认的[object Object]字符串。每个类型数据嵌套在types数组的type.name字段里,需要提取后再展示。

修改后的JavaScript代码

const name = document.getElementById('name')
const id = document.getElementById('id')
const type = document.getElementById('type')
const baseexperience = document.getElementById('baseexperience')
const button = document.querySelector('.myButton');

button.addEventListener('click', (e) => {
  e.preventDefault()
  const randomPokemon = Math.ceil(Math.random() * 1017)
  fetch(`https://pokeapi.co/api/v2/pokemon/${randomPokemon}`)
    .then(response => response.json())
    .then(pokemon => {
      console.log(pokemon)
      name.innerHTML = pokemon['name']
      id.innerHTML = pokemon['id']
      // 提取类型名称并拼接成字符串
      type.innerHTML = pokemon.types.map(item => item.type.name).join(', ')
      baseexperience.innerHTML = pokemon['base_experience']
    })
})

代码说明

  • pokemon.types.map(item => item.type.name):遍历类型数组,提取每个元素里的type.name,得到一个纯类型名称的数组(比如["fire", "flying"])
  • .join(', '):将数组元素用逗号加空格连接成一个可读的字符串,最终展示为fire, flying

HTML代码(无需修改)

<body>
  <div id="name"></div>
  <div id="id"></div>
  <div id="type"></div>
  <div id="baseexperience"></div>
  <button class="myButton">Catch 'em all</button>
</body>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 22:58:25