簡體   English   中英

.map 不是函數(api 結果)

[英].map is not a function (api result)

我正在嘗試映射 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>

https://pokeapi.co/api/v2/pokemon/ditto返回對象而不是數組(同上 pokemon)。 map是 Array 的函數,這就是您捕獲此錯誤的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM