前言
本文只是单纯的想给一些基础差的朋友分析一下如何去实现原理。
1. 先看函数的规定
上图是map 的规范
两个参数:
-
第一个参数是 callbackfn 回调函数,
- value 是遍历到当前的值
- index 是遍历到当前的下标
- array 是被遍历的原数组
-
第二个参数是 thisArg: 是任意对象。是用来替换遍历函数上下文 this 的指向。
返回值: 数组
因此,map 函数的意义就是对整个属性进行一次改变,并返回一个相同长度的数组。
2. 先看数组的 map 的基本使用
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
复制代码
- 特点:
- array1 不等于 array2。
- 元素如果是 引用数据类型,则会浅拷贝。
3. 手写实现 map
// 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
}
复制代码
就是如此的简单。
转载于:https://juejin.im/post/5cf232385188254c5726a291