Foreword
This article just simply want to give some poor foundation friends how to analyze the implementation principle.
1. The provisions of look at the function
The figure is a map specification
Two parameters:
-
The first parameter is callbackfn callback function,
- value is traversed to the current value
- index is traversed to the current index
- array is traversed original array
-
The second parameter is thisArg : any object. Alternatively traversal function is used to point to this context.
Returns: Array
Thus, the significance map is a function of a change of the entire attributes, and returns an array of the same length.
2. Look at the map using the basic array
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
复制代码
- Features:
- array1 not equal array2.
- If the data type is a reference element, it will be shallow copy.
3. Handwriting realization 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
}
复制代码
It is so simple.
Reproduced in: https: //juejin.im/post/5cf232385188254c5726a291