JavaScript中的常用高阶函数
这是在前端早读课中看到的JavaScript高阶函数,觉得有用便顺手记下来。
1.filter
const people = [
{name: 'John Doe',age: 16},
{name: 'Thomas Calls',age: 19},
{name: 'Liam Smith',age: 20},
{name: 'John Doe',age: 16}
]
筛选出大于等于18岁的人:
//普通做法实现过滤掉不足18岁的人 箭头函数不明白的去搜一下
const peopleAbove18 = (collection) => {
const results = [];
for (let i = 0;i < collection.length:i++){
const person = collection[i];
if(person.age >= 18){
result.push(person)
}
}
return results;
};
//利用filter达到同样效果
const peopleAbove18 = (collection) => {
return collection.filter((people) => person.age >= 18);
};
filter()接受一个函数参数,这个函数接受一个数组对象,再返回满足某条件的数组对象。filte()实现的是对数组对象中的每个元素进行判别,再把经过筛选后的数组对象返回
2.map
const coffeeLovers = {'John Doe','Liam Smith','Jessy Pinkman'};
//普通做法实现把是否爱喝咖啡的属性加入结果
const addCoffeeLoverValue = (collection) => {
const result = [];
for(let i = 0;i < collection.length;i++){
const person = collection[i];
if(coffeeLovers.includes(person.name)){
person.coffeeLover = true;
}
else{
person.coffeeLover = false;
}
result.push(person);
}
}
//利用map达到同样效果
const incrementAge = (collection) =>{
return collection.map((person)=>{
person.coffeeLover = coffeeLovers.includes(person.name);
})
}
map()接受一个函数参数,这个函数接受一个数组对象,map()实现的其实是遍历这个数组对象,对数组中每个元素进行操作。
3.reduce
//普通方法实现计算person中所有人的年龄和 forEach参考我写的‘JavaScript中语句’一文
const sumAge = (collection) => {
let num = 0;
collection.forEach((person)=>{
num += person.age;
});
return num;
}
//使用reduce实现同样的效果
const sumAge = (collection) => collection.reduce((sum,person) => {
return sum + person.age;
})
reduce()方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
语法:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
参数 | 描述 |
---|---|
total | 必需。初始值, 或者计算结束后的返回值。 |
currentValue | 必需。当前元素 |
currentIndex | 可选。当前元素的索引 |
arr | 可选。当前元素所属的数组对象。 |
4.总结
其实自己写完才知道这个标题实在是起的有迷惑性,这不过是数组对象的几个常用方法,硬是被说成了JavaScript常用高阶函数。虽然确实切合高阶函数以函数作为参数的定义,但还是感觉不应叫这个,以后有空会再研究JavaScript中的高阶函数。