JavaScript常见手写函数系列(一)

(一下均为简单实现,没有考虑过多的edge case) 

对于方法的基本使用不熟悉的话,可以上MDN查阅

对于map方法是十分重要的,React中没有像Vue中v-for指令一样的指令,只能传递数组,所以我们需要用到map方法对数组中的数据进行一些包装

map实现

Array.prototype.map = function (fn, thisValue = undefined) {

    const res = [] //初始化返回结果

    const target = fn.bind(thisValue) //为目标函数绑定this返回target函数

    for (let i = 0; i < this.length; i++) {
        //将target函数的返回值塞到res中
        res.push(target(this[i], i, this))
    }

    return res
}

reduce实现

Array.prototype.treduce = function (fn, initialValue) {
  //对返回值初始化,传了就用传递的参数,没传就是使用的数组第一项
  let res = initialValue === undefined ? this[0]: initialValue

  //遍历的时候也要判断是否传递参数
  for (let i = initialValue === undefined ? 1 : 0; i < this.length; i++) {
    res = fn(res, this[i], i, this)
  }
  return res
}

filter实现

Array.prototype.filter = function (fn, thisObject) {
  //初始化返回结果
  const res = []

  // 为目标函数绑定this
  const target = fn.bind(thisObject)

  // 遍历执行目标函数,往res中塞执行结果为true的元素
  for (let i = 0; i < this.length; i++) {
    if (target(this[i], i, this)) {
      res.push(this[i])
    }
  }

  return res
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值