高阶函数

什么是高阶函数

如果一个函数接受另一个函数作为参数,那么该函数就是高阶函数

常见的高阶函数

手写 forEach

js
Array.prototype.myForEach = function (callback) {
  if (typeof callback !== "function") {
    throw new Error("parameter must be a function");
  }
  for (let i = 0; i < this.length; i += 1) {
    callback.call(this, this[i], i);
  }
};

手写 map

js
Array.prototype.myMap = function (callback) {
  if (typeof callback !== "function") {
    throw new Error("parameter must be a function");
  }
  const res = [];
  for (let i = 0; i < this.length; i += 1) {
    res.push(callback.call(this, this[i], i, this));
  }
  return res;
};

手写 reduce

js
Array.prototype.myReduce = function (callback, init) {
  if (typeof callback !== "function") {
    throw new Error("parameter must be a function");
  }

  let pre = init;
  let i = 0;
  if (!init) {
    pre = this[0];
    i = 1;
  }

  for (i; i < this.length; i += 1) {
    pre = callback.call(this, pre, this[i], this);
  }
  return pre;
};

手写 filter

js
Array.prototype.myFilter = function (callback) {
  if (typeof callback !== "function") {
    throw new Error("parameter must be a function");
  }

  const res = [];
  for (let i = 0; i < this.length; i += 1) {
    if (callback.call(this, this[i], i, this)) {
      if (typeof this[i] === 'object') {
        res.push(Object.create(this[i]))
      } else {
        res.push(this[i]);
      }
    }
  }
  return res;
};

手写 every

js
Array.prototype.myEvery = function (callback) {
  if (typeof callback !== "function") {
    throw new Error("parameter must be a function");
  }

  for (let i = 0; i < this.length; i += 1) {
    if (!callback.call(this, this[i], i, this)) {
      return false
    }
  }
  return true
}

手写 some

js
Array.prototype.mySome = function (callback) {
  if (typeof callback !== "function") {
    throw new Error("parameter must be a function");
  }

  for (let i = 0; i < this.length; i += 1) {
    if (callback.call(this, this[i], i, this)) {
      return true
    }
  }
  return false
}

沿着联系继续阅读

0 条反向链接

引用本文

还没有公开笔记引用这里。

本文提到

暂时没有其他关联。

在花园里找一找

输入关键词开始搜索。按 Esc 关闭。