Array.prototype.map()

2021-07-15  本文已影响0人  Lnevan

1.语法

2.手写

let arr = [1,2,33,4,6,7]
Array.prototype.myMap = function (callback,thisValue) {
  if(Object.prototype.toString.call(callback) != "[object Function]") { //判断传给callback的实参是否是函数,不是函数则报错
    throw new TypeError(callback + "is not a function!")
  }
  let res = [] //因为该方法不能改变原数组
  //所以要新建一个数组来接收符合要求的数值
  const _this = this
  const newThis = thisValue? thisValue : _this //如果传了thisValue则用用户传过来的this
  _this.forEach((item,index) => { //遍历当前数组
    res.push(callback.call(newThis,item,index,_this))
    //用变量接收map方法的结果会发现有值所以需要return res,然后就是遍历该数组,在函数对当前元素
    //进行操作,例如console.log(item)就是把当前的元素打印出来,所以就会有种map函数有遍历的功能
  })
  return res
}
arr.myMap((item,index) => {
  console.log(index + ":" + item) 
  //0:1
  // 1:2
  // 2:33
  // 3:4
  // 4:6
  // 5:7
})
上一篇 下一篇

猜你喜欢

热点阅读