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

标签 javascript arrays foreach iife

我有一个位于 IIFE 内的数组,然后有一个 forEach 循环来迭代这些数组项,但我不知道如何使用 forEach 循环调用该函数。

//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>")
  }
});

我可以使用以下命令调用 console.log 中的项目;

console.log(pokemonRepository.getAll());

但我想使用 DOM 中的 forEach 循环来调用存储库。

最佳答案

您自己回答了 - 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>")
  }
});

关于javascript - 如何使用 forEach 循环在 IIFE 中调用数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75296994/

相关文章:

C# `foreach` 行为 - 说明?

c++ - 为什么不能 for_each 修改它的仿函数参数?

javascript - 谷歌 AdSense : Changing a background color to transparent

javascript - 找不到要加载的主 socket 'XYZComponent'

javascript - 如何获得浏览器的正确视口(viewport)大小

javascript - 从 json 创建数组,但值有异常(exception)

另一个 Bootstrap 模式中可用的 Javascript 函数

javascript - 动态生成集成参数的函数数组?

javascript - 过滤具有多个属性的两个数组

c# - 如何跳过 Foreach 中的记录