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

JavaScript调用Pokemon API时如何渲染宝可梦的第二种类型?

Fixing Pokemon Type Rendering for Single-Type Pokemon

Hey there! I see the issue you're running into—some Pokemon only have one type, so trying to access apiTypes[1] directly causes problems (since that index doesn't exist for those Pokemon). Let's fix this so your code smoothly handles both single-type and dual-type Pokemon.

The Root of the Problem

When a Pokemon only has one type, pokemon.apiTypes is an array with just one element. Trying to access pokemon.apiTypes[1].image will result in undefined.image, which breaks the image rendering (you might even see an error in your browser's console about this!).

The Simple Solution

Instead of hardcoding indexes for each type, loop through the apiTypes array to render all available types. This way, whether a Pokemon has 1 or 2 types, all of them will show up correctly without any errors.

Modified Working Code

Here's your updated code with the key fixes highlighted:

const pokemonContainer = document.querySelector('.pokemon-container')
let pokemonData = []

async function fetchPokemon(){
  await fetch("https://pokebuildapi.fr/api/v1/pokemon")
    .then((res) => res.json())
    .then((data) => pokemonData = data);

  console.log(pokemonData);
  pokemonDisplay()
};

function pokemonDisplay(){
  pokemonContainer.innerHTML = pokemonData
    .map((pokemon) => 
      `
      <div class="card">
        <h2>#${pokemon.id}  ${pokemon.name}</h2>
        <img src="${pokemon.image}" id="pic">
        <!-- Dynamically render all types in the array -->
        ${pokemon.apiTypes.map(type => `<img src="${type.image}" class="type">`).join('')}
        <ul>
          <li>PV  ${pokemon.stats.HP}</li>
          <li>Att  ${pokemon.stats.attack}</li>
          <li>Def  ${pokemon.stats.defense}</li>
        </ul>
      </div>
      `
    ).join("")
};

window.addEventListener('load', fetchPokemon);

Key Changes Breakdown:

  1. Dynamic Type Rendering: Replaced the hardcoded single type image with pokemon.apiTypes.map(...)—this generates an <img> tag for every type in the array, no matter how many there are.
  2. Unique Classes Instead of IDs: Changed id="type" to class="type"—IDs must be unique on a page, so using a class makes more sense when you might have multiple type images per card.
  3. Join the Array: Used .join('') to convert the array of type image strings into a single HTML string that gets inserted into the card.

Bonus: Edge Case Handling (Optional)

If you want to cover the rare scenario where a Pokemon has no types (though the API likely doesn't have any), you can add a quick fallback:

${pokemon.apiTypes.length > 0 
  ? pokemon.apiTypes.map(type => `<img src="${type.image}" class="type">`).join('')
  : '<span>No types available</span>'}

Now your code is robust enough to handle any number of types the API returns!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 09:55:14