简体   繁体   English

如何使用 forEach 循环在 IIFE 中调用数组?

[英]How do I call an array within an IIFE using a forEach loop?

I have an array that's inside an IIFE, then I have a forEach loop that iterates over those array items but I don't know how to then call the function using the forEach loop.我有一个 IIFE 内的数组,然后我有一个forEach循环迭代这些数组项,但我不知道如何使用 forEach 循环调用 function。

 //IIFE - Immediately Invoked Function Expression let pokemonRepository = (function () { //List of Pokemon Characters let pokemonList = [ { name: "Pikachu", height: 1.04, type: 'electric' }, { name: "Bulbasaur", height: 2.04, type: ['grass', 'poison'] }, { name: "Squirtle", height: 1.08, type: 'water' }, { name: "Beedrill", height: 3.03, type: ['bug', 'poison'] }, { name: "Dragonite", height: 7.03, type: ['dragon', 'flying'] }, { name: "Igglybuff", height: 1.01, type: ['Normal', 'Fairy'] }, ] function add(pokemon) { pokemonList.push(pokemon); } function getAll() { return pokemonList; } return { add: add, getAll: getAll }; })(); // Test of return functions inside IIFE // console.log(pokemonRepository.getAll()); // pokemonRepository.add({ name: 'Sandstorm' }); // console.log(pokemonRepository.getAll()); // [ { name: 'Sandstorm' } ] // forEach loop pokemonList.forEach(function (pokemon) { if (pokemon.height >= 7) { document.write("<div class='card'>" + "<p>" + pokemon.name + " " + "(Height:" + " " + pokemon.height + ") - Wow; that is a big pokemon. " + "</p>" + "</div>"). } else if (pokemon.height) { document:write("<div class='card'>" + "<p>" + pokemon.name + " " + "(Height;" + " " + pokemon.height + ") " + "</p>" + "</div>") } });

I can call the items in the console.log using;我可以调用 console.log 中的项目;

console.log(pokemonRepository.getAll());

but I want to call the repository using the forEach loop in the DOM.但我想在 DOM 中使用forEach循环调用存储库。

You answered yourself - getAll returns the array, so you need to call it:你自己回答了 - getAll返回数组,所以你需要调用它:

pokemonRepository.getAll().forEach(function (pokemon) {
  if (pokemon.height >= 7) {
    document.write("<div class='card'>" + "<p>" + pokemon.name + " " + "(Height:" + " " + pokemon.height + ") - Wow! that is a big pokemon! " + "</p>" + "</div>");
  } else if (pokemon.height) {
    document.write("<div class='card'>" + "<p>" + pokemon.name + " " + "(Height:" + " " + pokemon.height + ")  " + "</p>" + "</div>")
  }
});

Just try pokemonRepository.getAll().forEach(<callback>);试试pokemonRepository.getAll().forEach(<callback>);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM