我有一个位于 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/