6. 实现数组的map方法

数组的map() 方法会返回一个新的数组,这个新数组中的每个元素对应原数组中的对应位置元素调用一次提供的函数后的返回值。

用法:

const a = [1, 2, 3, 4];
const b = array1.map(x => x * 2);
console.log(b); // Array [2, 4, 6, 8]

实现前,我们先看一下map方法的参数有哪些

map方法有两个参数,一个是操作数组元素的方法fn,一个是this指向(可选),其中使用fn时可以获取三个参数,实现时记得不要漏掉,这样才算完整实现嘛

原生实现:

查看答案
// 实现
Array.prototype.myMap = function(fn, thisValue) {
let res = []
thisValue = thisValue||[]
let arr = this
for(let i=0; i<arr.length; i++) {
res.push(fn.call(thisValue, arr[i],i,arr)) // 参数分别为this指向,当前数组项,当前索引,当前数组
}
return res
}
// 使用
const a = [1,2,3];
const b = a.myMap((a,index)=> {
return a+1;
}
)
console.log(b) // 输出 [2, 3, 4]