JS高阶函数

JS高阶函数介绍

高阶函数

高阶函数是对其余函数进行操做的函数,能够将它们做为参数传递,或者是返回一个函数。 简单来讲,高阶函数是一个接收函数做为参数传递或者将函数做为返回值输出的函数。javascript

函数做为参数传递

Array.prototype.map

map() 方法建立一个新数组,其结果是该数组中的每一个元素都调用一个提供的函数后返回的结果。不改变原数组java

🌰:面试

将一个数组 [1, 2, 3, 4] 中的每一项扩大2倍:数组

const arr1 = [1, 2, 3, 4]
const arr2 = arr1.map(item => item * 2)

console.log(arr1); // [1, 2, 3, 4]
console.log(arr2); // [2, 4, 6, 8]
复制代码

Array.prototype.filter

filter() 方法建立一个新数组, 其包含经过所提供函数实现的测试的全部元素。若没有经过测试,则返回空数组;不改变原数组闭包

🌰: 对数组 [1, 3, 2, 4, 3, ,4 ,6, 3, 4, ,5 ,3 ,1] 进行去重处理:函数

const arr1 = [1, 3, 2, 4, 3, ,4 ,6, 3, 4, ,5 ,3 ,1]
const arr2 = arr1.filter((item, index, self) => {
    return self.indexOf(item) === index
})
console.log(arr1) // [1, 3, 2, 4, 3, ,4 ,6, 3, 4, ,5 ,3 ,1]
console.log(arr2) // [1, 3, 2, 4, 6, 5]
复制代码

Array.prototype.reduce

语法: arr.reduce(callback[, initialValue])测试

reduce() 方法对数组中的每一个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。ui

reduce() callback函数接受四个参数:spa

  1. accumulator(acc) (累加器)
  2. currentValue(cur)(当前值)
  3. currentIndex(idx)(当前索引) (可选)
  4. array(arr)(原数组) (可选)

reduce 函数的返回值分配给累计器,该返回值在数组的每一个迭代中被记住,并最后成为最终的单个结果值。prototype

initialValue 初始值(可选)。

做为第一次调用 callback函数时的第一个参数的值。 若是没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。

🌰:累加案例

  • 无初始值
const arr = [1, 2, 3, 4, 5]
let sum = arr.reduce((acc, cur, idx, arr) => {
    return acc + cur
})

console.log(sum) // 15
复制代码
  • 有初始值
const arr = [1, 2, 3, 4, 5]
let sum = arr.reduce((acc, cur, idx, arr) => {
    return acc + cur
}, 10)

console.log(sum) // 25
复制代码

函数做为返回值输出

简单说就是返回一个函数。

isType 函数

判断函数类型经常使用的是 Object.prototype.toString.call() 来获取对应对象返回的字符串;

eg:

console.log(Object.prototype.toString.call('hello world')); // [object String]
复制代码

能够对类型判断进行封装成一个 isType 方法:

let isType = type => obj => {
  return Object.prototype.toString.call(obj) === '[object ' + type + ']'
}

console.log(isType('String')('hello'))     // true
console.log(isType('Number')(123))         // true
console.log(isType('Array')([1, 2, 3]))   // true
console.log(isType('Object')({
  name: 'Tom'
}))    // true

复制代码

这里就是一个高阶函数,由于 isType 函数将 obj => { ... } 这一函数做为返回值输出。

add 函数

打印函数时会自动调用 toString() 方法。eg:

let sum = function () {
  return 1 + 2
}

console.log(sum)
// ƒ() {
// return 1 + 2
// }

sum.toString = function () {
  return 12
}

console.log(sum) // f 12
console.log(sum.toString()) // 12

// 打印函数的时候会自动调用 toString 方法,所以能够重写 toString 方法来修改返回值;

复制代码

面试题, 用 JS 实现一个无限累加的函数 add。

add(1).toString()   // 1
add(1)(2).toString() // 3
add(1)(2)(3).toString() // 6

复制代码

实现:

function add(a) {
    function sum(b) { // 闭包
        a = a + b
        return sum
    }
    
    sum.toString = function () { // 重写 toString 方法
        return a
    }
    
    return sum
}
console.log(add(1)) // f 1 (function)
console.log(add(1).toString()) // 1
console.log(add(1)(2).toString()) // 3

复制代码
相关文章
相关标签/搜索