在pokedex项目中调用数组

Calling an array in pokedex project

提问人:ryanl 提问时间:9/18/2023 最后编辑:lloydryanl 更新时间:9/19/2023 访问量:60

问:

我最近设计了一个 pokedex,并创建了一个包含所有 pokemon ID 和类的数组。

const pokedex = [
{
  pokemon: 'bulbasaur',
  dexInfo: [
    { dexName: 'bulbasaur-name' },
    { specs: 'bulbasaur-specs' },
    { desc: 'bulbasaur-desc' }
  ],
  dexNumber: 'bulbasaur-no',
  primaryType: 'grass-one',
  secondaryType: 'poison-two'
}
];

function turnOnPokedex() {
  console.log('turn-on')
  pokemonImage.classList.remove('hide')
  pokemonInfo.classList.remove('hide')
  pokemonTypeOne.classList.remove('hide')
  pokemonTypeTwo.classList.remove('hide')
  dexNo.classList.remove('hide')

  for (let i = 0; i < pokedex.length; i++) {
  
  }

  nextPokemon()
}

let pokemonImage = document.getElementById('pokemon')
let pokemonInfo = document.getElementById('dex-info')
let pokemonTypeOne = document.getElementById('type-one')
let pokemonTypeTwo = document.getElementById('type-two')
let dexNo = document.getElementById('dex-number')
<img id="bulbasaur" src="images/pokemon/bulbasaur.png" width="250" height="220">
<div id="bulbasaur-no"><strong>001</strong></div>
<div id="bulbasaur-name">Bulbasaur</div>
<div id="bulbasaur-specs">
  Species: Seed Pokemon<br><br>
  Height: 2'04<br><br>
  Weight: 15.2lbs(6.9kg)
</div>
<div id="bulbasaur-desc">
A strange seed was planted on<br><br> its back at birth. The plant<br><br> sprouts and grows with this<br><br> Pokémon.
<div\>
<div class="grass-one">Grass</div>
<div class="poison-two">Poison</div>

但是,每当我尝试调用此函数时,整个 pokedex 都会立即出现,而不仅仅是从 bulbasaur 开始。关于如何解决这个问题的任何想法?谢谢。

JavaScript 数组 函数 变量 getElementById

评论

0赞 lucs100 9/18/2023
您在 Javascript 中的 for 循环是空的 - 你是想在里面调用吗?nextPokemon()
0赞 David 9/18/2023
您能否将这些代码片段更新为可运行的最小可重现示例来演示该问题?我们不知道这些变量中有什么调用,做什么,具体引用哪些元素,为什么有一个空循环什么都不做,等等。turnOnPokedex()nextPokemon()
0赞 Barmar 9/18/2023
该怎么办?nextPokemon()
0赞 ryanl 9/18/2023
我最初确实在那里有“pokedex[i]”,但我删除了它,因为它不起作用
0赞 Barmar 9/18/2023
为什么要把所有的绳子都放在 obect 周围?()

答:

1赞 Mr. Polywhirl 9/19/2023 #1

JSON 数据不应看起来像 HTML 标记。每个 Pokédex 条目本质上都应该相当平坦。由于神奇宝贝通常有一种或两种类型,因此将它们存储在数组中是更好的选择。

如果您想要 Pokédex 中的上一个/下一个按钮,则必须存储当前索引。此外,您应避免使用 ID 属性。类名是一种更通用的方法。

const entry = document.querySelector('.pkmn-entry');
let currentIndex = 0;

const pokedex = [{
  id: 1,
  name: 'Bulbasaur',
  species: 'Seed Pokemon',
  height: 0.7, /* meters */
  weight: 6.9, /* kg */
  description: 'A strange seed was planted on its back at birth. The plant sprouts and grows with this Pokémon',
  types: ['grass', 'poison'],
}, {
  id: 2,
  name: 'Ivysaur',
  species: 'Seed Pokemon',
  height: 1.0, /* meters */
  weight: 13.0, /* kg */
  description: 'When the bulb on its back grows large, it appears to lose the ability to stand on its hind legs.',
  types: ['grass', 'poison'],
}, {
  id: 3,
  name: 'Venusaur',
  species: 'Seed Pokemon',
  height: 2.0, /* meters */
  weight: 100.0, /* kg */
  description: 'The plant blooms when it is absorbing solar energy. It stays on the move to seek sunlight.',
  types: ['grass', 'poison'],
}];

render();

function turnOnPokedex() {
  entry.classList.toggle('hide');
}

function navigate(button) {
  const offset = button.dataset.direction === 'prev' ? -1 : 1;
  // Cycle through
  currentIndex = (currentIndex + offset + pokedex.length) % pokedex.length;
  render();
}

function render() {
  const p = pokedex[currentIndex];
  
  const resource = `${p.id.toString().padStart(4, '0')}${p.name}.png`;
  entry.querySelector('.pkmn-img').src = getAbsolutePath(resource, 'https://archives.bulbagarden.net/media/upload');
  entry.querySelector('.pkmn-img').alt = p.name;
  entry.querySelector('.pkmn-no').textContent = p.id.toString().padStart(3, '0');
  entry.querySelector('.pkmn-name').textContent = p.name;
  entry.querySelector('.pkmn-specs').innerHTML = `
    Species: ${p.species}<br />
    Height: ${metersToFeet(p.height)}<br />
    Weight: ${round(kgToLbs(p.weight), 1)} lbs
  `;
  entry.querySelector('.pkmn-desc').textContent = p.description;
  entry.querySelector('.pkmn-types').innerHTML =
    p.types
      .map(type => `<div data-type="${type}">${capitalize(type)}</div> `)
      .join('');
}

function getAbsolutePath(filename, baseUrl) {
  const hash = CryptoJS.MD5(filename.replace(/ /g, '_')).toString();
  return `${baseUrl}/${hash[0]}/${hash.substring(0, 2)}/${filename}`;
};

function capitalize(word) {
  return word[0].toUpperCase() + word.slice(1).toLowerCase();
}

function metersToFeetAndInches(meters) {
  const inches = meters * 39.3701;
  return {
    feet: Math.floor(inches / 12),
    inches: Math.round(inches % 12)
  };
}

function metersToFeet(meters) {
  const { feet, inches } = metersToFeetAndInches(meters);
  return `${feet}'${inches}"`;
}

function kgToLbs(kg) {
  return kg * 2.20462;
}

function round(n, p = 2) {
  return (e => Math.round(n * e) / e)(Math.pow(10, p));
}
.pkmn-entry .pkmn-no {
  font-weight: bold;
}

.pkmn-entry .pkmn-types div {
  display: inline-block;
}

.hide {
  display: none;
}

.pkmn-types [data-type] { padding 0.5rem; }
.pkmn-types [data-type="grass"] { background: #AFA; }
.pkmn-types [data-type="poison"] { background: #FDF; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/core.min.js" integrity="sha512-t8vdA86yKUE154D1VlNn78JbDkjv3HxdK/0MJDMBUXUjshuzRgET0ERp/0MAgYS+8YD9YmFwnz6+FWLz1gRZaw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/md5.min.js" integrity="sha512-3sGbaDyhjGb+yxqvJKi/gl5zL4J7P5Yh4GXzq+E9puzlmVkIctjf4yP6LfijOUvtoBI3p9pLKia9crHsgYDTUQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<button type="button" onclick="turnOnPokedex()">Toggle Pokedex</button>
<div class="pkmn-entry hide">
  <img class="pkmn-img" src="" alt="Bulbasaur" width="250" height="220">
  <div class="pkmn-no">001</div>
  <div class="pkmn-name">Bulbasaur</div>
  <div class="pkmn-specs">
    Species: Seed Pokemon<br />
    Height: 2'04<br />
    Weight: 15.2lbs(6.9kg)
  </div>
  <div class="pkmn-desc">
    A strange seed was planted on its back at birth. The plant sprouts and grows with this Pokémon.
  </div>
  <div class="pkmn-types">
    <div data-type="grass">Grass</div>
    <div data-type="poison">Poison</div>
  </div>
  <div class="actions">
    <button type="button" data-direction="prev" onclick="navigate(this)">Prev</button>
    <button type="button" data-direction="next" onclick="navigate(this)">Next</button>
  </div>
</div>

评论

0赞 ryanl 9/20/2023
感谢您@Mr Polywhirl 和其他所有人的建议。我将使用它并跟进它。