在JSON数据集中的此处,循环仅在第一个神奇宝贝上进行迭代,即仅对Bulbasaur为true。如果您输入其他任何宠物小精灵的名字,则显示“未找到”。如果您输入“ Ivysaur”或任何其他神奇宝贝名称(如“ Venusaur”),则不会显示。在下面查看我的代码。

    let findpokemongame = {https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json} //click the link to find the JSON dataset

        var findname = window.prompt("Enter Pokemon Name")
let checkname = function(findname, findpokemongame) {
  for (let thispokemon in findpokemongame.pokemon) {
    if (findpokemongame.pokemon[thispokemon].name == findname) {
      let pokemondetails = findpokemongame.pokemon[thispokemon];
      console.log(pokemondetails);
      for (info in pokemondetails) {
        if (typeof pokemondetails[info][0] === 'object') {
          pokemondetails[info] = pokemondetails[info].map(o => o.name)
        }

        alert(info + " : " + pokemondetails[info] + "\n")

      }
    }
    else{
      alert('Not found');
      break;
    }
  }
}

checkname(findname, findpokemongame)

最佳答案

您的代码非常嵌套且复杂。就个人而言,我会使用array.find来查找神奇宝贝并简化代码。找到它之后,就可以对其进行其他(单独的)操作,并希望所有错误都会变得显而易见:

const foundPokemon = findpokemongame.pokemon.find(pokemon => pokemon.name === findname);

// check foundPokemon
if (foundPokemon) {
  // once found extract any details..
} else {
  // pokemon name not found
}


您如何处理名称案例?比较它们之前,最好将用户输入名称和json数据宠物小精灵名称都转换为小写(string.toLowerCase())。

关于javascript - 循环未在所有JSON数据集上迭代,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55318102/

10-10 05:09