美文网首页
JavaScript手写JS的Array.map方法

JavaScript手写JS的Array.map方法

作者: 六寸光阴丶 | 来源:发表于2020-04-06 17:00 被阅读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' ]

相关文章

网友评论

      本文标题:JavaScript手写JS的Array.map方法

      本文链接:https://www.haomeiwen.com/subject/ykvbphtx.html