js中map的实现

JS中map的实现

思路分析

map是所有数组都可以用的方法,因此我们可以将方法挂在到Array.prototype上去
之后所有的数组都可以访问到这个方法
map函数,接收一个函数当作参数,并且这个函数有返回值,
之后对数组中每个元素都执行这个函数,最后将所有的执行结果返回

代码实现

Array.prototype._map = function (fn) {
 // 传入的fn如果不是函数则直接返回
 if (typeof (fn) !== 'function') return
 // map方法会返回新数组
 const result = []
 // 给数组中的每一个方法都执行一次这个函数,并将返回值添加到result数组中
 // this指代的是当前调用的数组
 for (let i = 0; i < this.length; i++) {
   result.push(fn(this[i],i,this))
 }
 return result
}
let arr = [1, 2, 3, 4, 5, 6]
// 测试
console.log(arr._map(item => item + 'aaa'))
// 输出结果:[ '1aaa', '2aaa', '3aaa', '4aaa', '5aaa', '6aaa' ]
posted @ 2022-12-16 11:37  含若飞  阅读(642)  评论(0编辑  收藏  举报