gpt4 book ai didi

javascript - 迭代数组对象

转载 作者:行者123 更新时间:2023-11-30 14:37:28 26 4
gpt4 key购买 nike

我正在尝试编写一个函数,将“弱点”作为输入并给出所有具有该弱点的神奇宝贝的名称。

考虑以下 JSON:

访问https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json

var pokemonWeakness = function(weaknessOfPokemon,allPokemon){
for( x in allPokemon){
if(weaknessOfPokemon==allPokemon[x].weaknesses){
console.log('pokemon with this weaknesses are: '+allPokemon[x].name)
}else{
null
}
}
}

var weaknessOfPokemon = prompt('enter the weaknesses of pokemon')
pokemonWeakness(weaknessOfPokemon,pokemonData.pokemon)

这个函数的问题是没有返回任何数据。

最佳答案

Filter通过检查它们的 weaknesses 数组 includes 来得到 pokemon 数组weaknessOfPokemon。使用 Array.map()将名称提取到数组:

function findByPokemonWeakness(weaknessOfPokemon, pokemons){
return pokemons.filter((o) => o.weaknesses.includes(weaknessOfPokemon))
.map((o) => o.name);
}

fetch('https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json')
.then(r => r.json())
.then(d => console.log(findByPokemonWeakness('Fire', d.pokemon)));

关于javascript - 迭代数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50200449/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com