将indexOf与API数据一起使用受变量中字符串顺序的影响

问题描述

我正在使用具有每个Pokemon信息的API制作Pokedex。有些神奇宝贝有两种类型,但现在我只是展示它们的第一种(主要)类型。因此,如果它们是草/毒药类型,那么我只是在显示草。每个神奇宝贝的卡片的背景颜色也取决于它们的主要类型。

示例:

const colors = {
    grass: '#63BB5B',fire: '#FF9C54',water: '#4E90D5',electric: '#F3D23B',ice: '#74CEC0',//etc.
};
const main_types = Object.keys(colors);

但是,我注意到,如果我的颜色变量中它们的主要类型在其次要类型之后,它将列出其次要类型以及颜色。例如,毒药列在错误之前,因此所有错误/毒药类型都将毒药列为其主要类型。

这是我的功能(main_types在上面的代码中):

function createPokemonCard(pokemon) {
    const pokemonEl = document.createElement('div');
    pokemonEl.classList.add('pokemon');
    const poke_types = pokemon.types.map(el => el.type.name);
    const type = main_types.find(mt => poke_types.indexOf(mt) > -1);
    const name = pokemon.name[0].toupperCase() + pokemon.name.slice(1);
    const card_color = colors[type];

    pokemonEl.style.backgroundColor = card_color;

    const pokeInnerHTML = `
    <div class="img-container">
    <img src="https://pokeres.bastionbot.org/images/pokemon/${pokemon.id}.png" />
    </div>
    <div class ="info">
      <span class="number">#${pokemon.id.toString().padStart(3,'0')}</span>
      <h3 class="name">${name}</h3>
      <small class="type">Type: <span>${type.charat(0).toupperCase() + type.slice(1)}</span></small>
    </div>
    `;

    pokemonEl.innerHTML = pokeInnerHTML;

    poke_container.appendChild(pokemonEl);
  }

我如何让我的函数选择其第一种类型,而与colors变量中的顺序无关?

解决方法

这会做,您只需要切换顺序 def countConsecutive (mainstr,substr,count): if substr in mainstr[:len(substr)]: count += 1 mainstr = mainstr[len(substr):] return countConsecutive (mainstr,count) #added return statement else: return count

,

router.get("",(req,res,next) => { const pageSize = +req.query.pagesize; const currentPage = +req.query.page; let fetchedHierarchs; const hierarchQuery = Hierarch.find().sort({name: 1,lastName: 1}); if (pageSize && currentPage) { hierarchQuery.skip(pageSize * (currentPage - 1)) .limit(pageSize); } hierarchQuery .then(documents => { fetchedHierarchs = documents; return Hierarch.countDocuments(); }) .then(count => { res.status(200).json(fetchedHierarchs); }); }); router.get("/moscow",next) => { Hierarch.find().then(document => { if (document) { res.status(200).json(document); } else { res.status(404).json({ message: "Hierarch not found!" }); } }); }); router.get("/:id",next) => { Hierarch.findById(req.params.id).then(document => { if (document) { res.status(200).json(document); } else { res.status(404).json({ message: "Hierarch not found!" }); } }); }); 在其元素中搜索满足该谓词的第一个值。因此,与其在主要类型中搜索商品类型,不如在商品类型中查找第一个主要类型。

Array#find