js中常见的高阶函数

什么是高阶函数?

接收一个函数作为参数的函数

常见的高阶函数

reduce()

接收一个函数作为累加器,从左到右数组中的值依次缩减,最后累加成一个数

语法:

reduce(funtion(total, currentNum, currentIndex, arr){}, initial)

total: 当前计算结果

currentNum:当前遍历到的值

currentIndex:当前遍历到的索引

arr:调用的数组对象

initial:初始值

实现原理

[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4);

map()

遍历数组的每一项,根据传入的参数进行操作,再将操作后的数组返回

[1, 2, 3, 4].map(funtion(x){
    return x*2
})
// [2, 4, 6, 8]

sort()

对数组中的元素进行排序,可以传入参数来规定排列顺序

[5, 9, 8, 3].sort(funtion(x, y){return y-x;}) //[9, 8, 5, 3]

filter()

对数组中的元素进行过滤,返回过滤后的数组

[1,5,10,30].filter(function (item) {
        return item <= 10;
    })
// [1, 5, 10]
原文地址:https://www.cnblogs.com/ashen1999/p/12713551.html