本文只是单纯的想给一些基础差的朋友分析一下如何去实现原理。数组
上图是map 的规范函数
两个参数:ui
第一个参数是 callbackfn 回调函数,this
第二个参数是 thisArg: 是任意对象。是用来替换遍历函数上下文 this 的指向。spa
返回值: 数组prototype
所以,map 函数的意义就是对整个属性进行一次改变,并返回一个相同长度的数组。code
let array1 = [ { a: 1 }, 2, 3, 4]
let obj = {}
let array2 = array1.map(function (item, index, arr) {
console.log(this === obj) // true
if (typeof item === 'object') {
item.a = 2
}
return item
}, obj)
console.log(array1[0] === array2[0]) // true
复制代码
// 1. 根据map 的特色,有两个入参
Array.prototype.myMap = function(callbackfn, thisArg) {
var newArray = [] // 新数组
// 对以前的数组进行 copy,新数组不影响原数组,可是值为引用类型仍是被同时被影响。
var currentArray = this.slice() // 方法一
// var currentArray = Array.prototype.slice.call(this) // 方法二
// var currentArray = [...this]
for(var i = 0; i < currentArray.length; i++) {
// 3.注入回调的三个参数,并能够有 thisArg 影响,上下文环境
newArray.push(callbackfn.call(thisArg, currentArray[i], currentArray))
}
return newArray
}
复制代码
就是如此的简单。cdn