# 06-高阶函数

# 什么是高阶函数

如果一个函数接受另一个函数作为参数,那么我们称该函数为高阶函数。

# js中常见的高阶函数

  • forEach和Map
  • reduce
  • filter
// 手写forEach和Map,reduce,filter
Array.prototype.myForEach = function (callback) {
    if (typeof callback !== 'function') {
        throw new Error('param must be function');
    }
    let len = this.length;
    for (let i = 0; i < len; i++) {
        callback.call(this, this[i], i, this);
        
    }
}
Array.prototype.myMap = function (callback) {
    if (typeof callback !== 'function') {
        throw new Error('param must be function');
    }
    let len = this.length;
    let newArr = [];
    for (let i = 0; i < len; i++) {
        newArr.push(callback.call(this, this[i], i, this));
    }
    return newArr;
}

Array.prototype.myReduce = function (callback, init) {
    if (typeof callback !== 'function') {
        throw new Error('param must be function');
    }
    let len = this.length;
    let i = 0;
    let total = init;
    if (init === undefined) {
        total = this[0];
        i = 1;
    }
    for (i; i < len; i++) {
        total = callback.call(this, total, this[i], i, this)
    }
    return total;
}

Array.prototype.myFilter = function (callback) {
    if (typeof callback !== 'function') {
        throw new Error('param must be function');
    }
    let len = this.length;
    let _newArr = [];
    for (let i = 0; i < len; i++) {
        if (callback.call(this, this[i], i, this)) {
            if (typeof this[i] === 'object') {
                _newArr.push(Object.create(this[i]));
            } else {
                _newArr.push(this[i]);
            }
        }
    }
    return _newArr;
}

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

# 编写自己的高阶函数

  • 保持纯函数和减少函数副作用
  • 选择call还是apply
// 自定义高阶函数:找出符合规则的属性名称
var obj = {
    name1: 1,
    name2: 2,
    name3: 3,
    name4: 4,
    name5: 5,
}

function findProperty(obj, callback) {
    if (typeof obj !== 'object') {
        throw new Error('param obj must be object');
    }
    if (typeof callback !== 'function') {
        throw new Error('param callback must be function');
    }
    var _obj = Object.create(obj);
    let _propertyArr = [];
    for (const key in _obj) {
        if (callback.call(_obj, _obj[key], key)) {
            _propertyArr.push(key);
        }
    }
    return _propertyArr;
}
console.log(findProperty(obj, (val,key)=> val > 2));
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