手写高阶函数

71 阅读1分钟

forEach

const names = ["james", "kobe", "qxy"]

  // 版本1
  // function xyForEach(fn) {
  //   let i
  //   for (i = 0; i < names.length; i++) {
  //     fn(names[i], i, names)
  //   }
  // }
  // xyForEach(function (item, index, names) {
  //   console.log("手写=============", item, index, names)
  // })


  // // 版本2
  // function xyForEach(fn, arr) {
  //   let i
  //   for (i = 0; i < arr.length; i++) {
  //     fn(arr[i], i, arr)
  //   }
  // }
  // xyForEach(function (item, index, names) {
  //   console.log("手写=============", item, index, names);
  // }, names)

  // 版本3
  // names.xyForEach = function (fn) {
  //   let i
  //   for (i = 0; i < this.length; i++) {
  //     fn(this[i], i, this)
  //   }
  // }
  // names.xyForEach(function (item, index, names) {
  //   console.log("手写=============", item, index, names);
  // })

  // 版本4 放原型链上,全局可用
  Array.prototype.xyForEach = function (fn) {
    for (var i = 0; i < this.length; i++) {
      fn(this[i], i, this)
    }
  }
  names.xyForEach(function (item, index, names) {
    console.log("手写=============", item, index, names);
  })

  //  原生
  names.forEach(function (item, index, names) {
    console.log("原生=============", item, index, names)
  })
  

find

 const students = [{
      id: 11,
      name: "qxy",
      age: 18
    },
    {
      id: 22,
      name: "james",
      age: 58
    },
    {
      id: 33,
      name: "kobe",
      age: 28
    },
    {
      id: 44,
      name: "why",
      age: 68
    },
  ]

  // 原生
  const findName = students.find(function (item, index, arr) {
    return item.id === 33
  })
  console.log("原生===>", findName);

  // 手写
  Array.prototype.xyFind = function (fn) {
    for (var i = 0; i < this.length; i++) {
      let isFlag = fn(this[i], i, this)
      if (isFlag) {
        return this[i]
      }
    }
  }
  const findStu = students.xyFind(function (item, index, arr) {
    return item.id === 22
  })
  console.log("手写===>", findStu);