JavaScript调用Pokemon API时如何渲染宝可梦的第二种类型?
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:
- 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. - Unique Classes Instead of IDs: Changed
id="type"toclass="type"—IDs must be unique on a page, so using a class makes more sense when you might have multiple type images per card. - 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

