【发布时间】:2016-11-23 16:42:38
【问题描述】:
我正在尝试使用一组对象进行函数式编程。
我想了解是否有一种更好或更简洁的方式来执行一系列函数,这些函数根据条件获取值并更新变量。
就像使用全局范围的变量一样,这是否令人不悦?无论如何我可以将狗的数量传递给“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();
【问题讨论】:
-
如果你想了解什么是函数式编程,我会竭诚推荐你learning basics of Haskell。 Haskell 甚至不支持你可能从命令式语言中知道的变量和循环等结构,所以你用 Haskell 编写的每个程序都必然不仅是函数式的,而且是纯函数式的。
-
您在特定意义上使用“函数式编程”,意思是“在数组上使用
forEach、map和filter”。有些人称其为函数式编程,因为您将这些方法传递给函数。它也许可以称为函数式编程,但只是勉强。 “函数式编程”实际上有更简洁、严谨的含义。您可能想知道这一点,并可以将您的问题重命名为“在 JS 中使用函数式数组方法”。 -
@torazaburo 虽然 Haskell 中的 FP 是一个准确的术语,但它不适用于 Javascript 等多范式语言。我想说高阶函数已经足够 FP 了。
标签: javascript functional-programming