JavaScript手写JS的Array.map方法

2020-04-06  本文已影响0人  六寸光阴丶

写在前面

如果本文对您有所帮助,就请点个关注吧!

手写map方法

源码

// _this默认为本身
Array.prototype.myMap = function (fn, _this = this) {
  let arr = []
  // 遍历数组,循环对元素执行回调函数
  for (let index in this) {
    // 执行回调函数时绑定this,并将结果push进新数组
    arr.push(fn.call(_this, this[index], index, this))
  }
  // 返回新数组
  return arr
}

// 设置新增原型为不可枚举,不会被for...in遍历出来
Object.defineProperty(Array.prototype, 'myMap', {
  enumerable: false
})

测试

// 测试
let arr = [1, 2, 3]
let newarr = arr.myMap(function (item, index, _this) {
  return item + ' ' + index + ' ' + _this[index] + ' ' + this[index]
}, [7, 8, 9])
console.log(newarr)

测试结果

// [ '1 0 1 7', '2 1 2 8', '3 2 3 9' ]
上一篇 下一篇

猜你喜欢

热点阅读