首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环未在所有JSON数据集上迭代

循环未在所有JSON数据集上迭代
EN

Stack Overflow用户
提问于 2019-03-24 04:34:15
回答 1查看 34关注 0票数 0

在这里的JSON数据集中,循环仅在第一个pokemon上迭代,即仅对Bulbasaur为true。如果你输入任何其他精灵宝可梦的名字,它会显示“找不到”。如果你输入“依维索尔”或者其他的精灵宝可梦名字,比如"Venusaur“,它就不会显示出来。看看我下面的代码。

代码语言:javascript
复制
    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)
EN

回答 1

Stack Overflow用户

发布于 2019-03-24 04:44:16

你的代码是非常嵌套和复杂的。就我个人而言,我会使用array.find来找到精灵并简化代码。一旦你找到了它,然后你可以对它进行其他(单独的)操作,希望任何错误都会变得显而易见:

代码语言:javascript
复制
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())。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55318102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档