实现forEach和map

# 实现forEach和map

//实现
Array.prototype.MyForEach = function (fn, context) {
  context = context || window;
  for (let i = 0; i < this.length; i++) {
    fn.apply(context, [this[i], i, this]);
  }
};

/**
 * map用法
 * 第一个参数是函数,第二个参数是this
 */

Array.prototype.MyMap = function (fn, context) {
  context = context || window;
  let res = [];
  for (let i = 0; i < this.length; i++) {
    res[i] = fn.call(context, this[i], i, this);
  }
  return res;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
上次更新: 2022/7/29 上午11:39:16