手写Array原型方法

本文介绍了JavaScript中三个重要的数组方法:reduce用于数组求和或聚合操作,flat用于扁平化多维数组,map则用于数组元素转换。详细解析了每个方法的参数及其实现原理,并提供了实例代码展示。

Array.prototype.reduce🔥

该方法接受两个参数,第一个是回调函数(该函数接受四个参数[累加器,当前值,当前索引(可选),reduce的数组(可选)]),第二个是初始值

Array.prototype.my_reduce = function (callback, ...rest) {
    let start = 0,  result;
    if (rest.length) {
        result = rest[0]
    } else {
        result = this[0]
        start ++
    }
    for (let i = start; i < this.length; i++) {
        result = callback(result, this[i], i, this)
    }
    return result;
}

Array.prototype.flat

该方法接受一个参数depth深度,该方法用来降低数组维度,该方法并不会改变原数组

Array.prototype.my_flat = function (depth) {
  const result = []
  for (let i = 0; i < this.length; i ++) {
    if (Array.isArray(this[i]) && depth !== 0) {
      result.push(...this[i].my_flat(--depth))
    } else {
      result.push(this[i])
    }
  }
  return result
}

Array.prototype.map⭐️

该方法接受两个参数callback&thisArgs,由于箭头函数没有this,所以若要想让第二个参数生效,不能使用箭头函数

箭头函数没有自己的this指针,通过 call() 或 apply() 方法调用一个函数时,只能传递参数(不能绑定this—译者注),他们的第一个参数会被忽略。(这种现象对于bind方法同样成立—译者注)

Array.prototype.my_map = function (callback, thisArgs) {
  const result = []
  for (let i = 0; i < this.length; i++) {
    if (thisArgs === undefined) {
      result.push(callback(this[i], i))
      continue
    }
    result.push(callback.call(thisArgs, this[i], i))
  }
  return result
}

其余方法的实现也类似以上三种,这里不再赘述,多谢您的浏览,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值