2. 高阶函数-函数作为参数、返回值
leezozz 12/17/2022 js
# 高阶函数(Higher-order funciton)
- 把函数作为参数传递给另一个函数
- 把函数作为另一个函数的返回结果(作为返回值)
# 高阶函数-函数作为参数
(1). 实现forEach
function forEach(arr, fn){
for(var i = 0; i < 5; i++) {
fn(arr[i])
}
let arr1 = [1, 2, 3, 4, 5]
forEach(arr1, function(item) {
console.log('item', item)
})
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
(2). 实现filter
function filter(arr, fn){
let result = []
for(var i = 0; i < 5; i++) {
if(fn(arr[i])) {
result.push(arr[i])
}
}
console.log('result', result)
return result
}
filter(arr1, function(item) {
return item % 2 === 0
})
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 函数作为返回值
function makeFn() {
return function(){
const a = 'hi hi hi'
console.log('aaa', a)
}
}
// 调用方法一
const fun = makeFn()
fun()
// 调用方法二
makeFn()()
// once函数 【注意:这里的返回值是函数,需要调用两次(同上例子),once()()】
function once(fn){
let done = false
console.log('once函数', done)
return function() {
console.log('once函数 ------------', done)
if(!done) {
done = true
// console.log('once函数')
return fn.apply(this, arguments)
}
}
}
// 这里调用了once函数
const pay = once(function(money) {
console.log('支付' + money + '元')
})
// 这里调用了once函数中的return的函数
pay(5)
pay(5)
pay(5)
pay(5)
pay(5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 高阶函数的意义
(1)抽象可以帮我们屏蔽细节,只需要关注与我们的目标
(2)高阶函数是用来抽象通用的问题
// 面向过程的方式
let array = [1, 2, 3]
for(let i = 0; i < array.length; i++) {
console.log(array[i])
}
1
2
3
4
5
2
3
4
5
// 高阶函数
let array1 = [1, 2, 3, 4, 5]
forEach(array1, item => {
console.log(item)
})
1
2
3
4
5
2
3
4
5
let r = filter(array, item => {
return item % 2 === 0
})
1
2
3
2
3