我是javascript的新手。我一直致力于一个程序,我在javascript中使用json数据集,将其分配给变量。数据集的链接如下。 https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json
我必须编写一个函数,我将一个小精灵的名字作为输入并显示其所有细节。下面是我使用的函数。
var list=pokeDex.pokemon;
var name=prompt("Enter the name of a pokemon");
// Function taking pokemon’s name as argument and displaying the
information of that pokemon.
function displayInfo(name)
{
for(var items in list)
{
if (name==list[items].name)
{
console.log(list[items]);
break;
}
else
{
//alert("error");
}
}
}
只有当else块中的alert语句是注释时,该函数似乎才能对列表中的所有pokemons正常工作。否则该函数会显示除数据集中第一个之外的所有pokemons的错误。
嗨通过名称过滤来简化你的逻辑,有像filter
这样的高阶函数迭代数组并得到一个返回true到你的条件,在这种情况下,条件将是口袋妖怪的名字。此外,当匹配字符串时,无论大写字母还是小写字母,都应用小写来匹配
代码可能如下所示:
const list = pokeDex.pokemon
const inputName = prompt("Enter the name of a pokemon")
const [ pokemonSelected ] = list.filter(pokemon => pokemon.name.toLowerCase() === inputName.toLowerCase())
console.log(pokemonSelected)
我为你做了一个小JSfiddle:https://jsfiddle.net/t8uep0ga/10/打开你的控制台并检查console.log()!希望能帮助到你!
您可以轻松简化逻辑
function displayInfo(searchName)
{
const filteredList = list.filter(poke => poke.name==searchName)
if (filteredList > 0)
{
console.log(filteredList[0]);
}
else
{
alert("error");
}
}
这将首先遍历列表并使用pokemon
搜索searchName
在你的代码中,如果第一个不是searchPokemon ieelse块而没有搜索剩余的列表,它会尝试给出错误警告。