我正在嘗試映射 api 結果以顯示資料,但是當我啟動我的代碼時,控制臺顯示TypeError: pokemons.map is not a function但我在另一個腳本中做了同樣的事情并且它在那里作業。我不明白為什么這次 .map 不起作用。
const result = document.getElementById('result');
const form = document.querySelector('form');
let pokemons = [];
async function fetchPokemon() {
fetch(`https://pokeapi.co/api/v2/pokemon/ditto`)
.then((res) => res.json())
.then((data) => (pokemons = data));
console.log(pokemons)
};
fetchPokemon();
function pokemonDisplay() {
result.innerHTML = pokemons.map(
(pokemon) =>
`
<h2>${pokemon.forms[0].name}</h2>
`
)
}
form.addEventListener('submit', (e) => {
e.preventDefault();
fetchPokemon().then(() => pokemonDisplay());
})
console.log(result);
<div class="app">
<form action="">
<label for="search">Entrez le nom d'un pokemon (en anglais)</label>
<input type="text" id="search" placeholder="ex : ditto">
</form>
<ul id="result"></ul>
</div>
uj5u.com熱心網友回復:
https://pokeapi.co/api/v2/pokemon/ditto回傳物件不是陣列(同上 pokemon)。
map是 Array 的函式,這就是您捕獲此錯誤的原因。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/339003.html
標籤:javascript 接口
