我正在使用对象数组进行函数式编程实验。
我想了解是否有更好或更清晰的方法来执行一系列基于条件更新变量的函数。像全局范围内的变量使用,这样做是否不被赞成?我是否可以将例如狗的数量传递给“updateDogsAmt”函数?等等...
是否有更好的方法可以完成这项工作?
我已经将这些函数分为更新DOM和逻辑的部分。
演示:JSFIDDLE
const animals = [
{name: 'Zack', type: 'dog'},
{name: 'Mike', type: 'fish'},
{name: 'Amy', type: 'cow'},
{name: 'Chris', type: 'cat'},
{name: 'Zoe', type: 'dog'},
{name: 'Nicky', type: 'cat'},
{name: 'Cherry', type: 'dog'}
]
let dogs = [];
function getDogs() {
//return only dogs
animals.map((animal) => {
if(animal.type === "dog") {
dogs.push(animal);
}
});
}
getDogs();
let dogsAmt = 0;
function getDogsAmt() {
//get dogs amount
dogsAmt = dogs.length;
}
getDogsAmt();
function updateDogsAmt() {
//update dom with dogs count
let dogsHTML = document.getElementById('dogs-amt');
dogsHTML.innerHTML = dogsAmt;
}
updateDogsAmt();
let otherAnimals = [];
function getOtherAnimals() {
//return other animals count
animals.map((animal) => {
if(animal.type != "dog") {
otherAnimals.push(animal);
}
});
}
getOtherAnimals();
let otherAnimalsAmt = 0;
function getOtherAnimalsAmt() {
otherAnimalsAmt = otherAnimals.length;
}
getOtherAnimalsAmt();
function updateOtherAnimalsAmt() {
//udate dom with other animals
let otherAmt = document.getElementById('other-amt');
otherAmt.innerHTML = otherAnimalsAmt;
}
updateOtherAnimalsAmt();
forEach
,map
和filter
。有些人之所以称其为函数式编程,是因为你将这些方法传递给函数。或许可以称之为函数式编程,但仅仅是勉强算得上。实际上,“函数式编程”有一个更加简洁、严谨的含义。你可能需要了解这一点,并将你的问题重命名为“在JS中使用函数式数组方法”。 - user663031