js实现map,filter,reduce,reduce实现map

map

Array.prototype.toMap = function (fn, thisValue) {
  if (Object.prototype.toString.call(fn) !== '[object Function]') {
    throw new Error('fn is not a function')
  }
  const arr = []
  const curArr = this

  for (let i = 0; i < curArr.length; i++) {
    arr.push(fn.call(thisValue, curArr[i], i, curArr))
  }
  return arr
}

filter

Array.prototype.toFilter = function (fn, thisValue) {
  if (Object.prototype.toString.call(fn) !== '[object Function]') {
    throw new Error('fn is not a function')
  }
  const arr = []
  const curArr = this

  for (let i = 0; i < curArr.length; i++) {
    const returnValue = fn.call(thisValue, curArr[i], i, curArr)
    if (returnValue) {
      arr.push(curArr[i])
    }
  }
  return arr
}

reudce

Array.prototype.toReduce = function (fn, initValue) {
  const curArr = this
  let firstValue
  let j = 0
  if (initValue) {
    firstValue = initValue
  } else {
    firstValue = curArr[0]
    j = 1
  }
  for(let i = j; i < curArr.length; i++) {
    firstValue = fn(firstValue, curArr[i], i, curArr)
  }
  return firstValue
}

reduce 实现 map

Array.prototype.reduceToMap = function (fn, context) {
  const curArr = this;
  function reudce(total, cur, index, curArr) {
    total.push(fn.call(context, cur, index, curArr))
    return total
  }
  const reuslt = curArr.reduce(reudce, [])
  return reuslt
}

console.log('color: #00e600', [1,2,3,4].reduceToMap(ele => ele*2));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值