什么是Array.map()
Array.map方法与Array.forEach类似,不同的是map方法会返回一个新的数组,这个新数组中的每个元素对应原数组中的对应位置的元素经传入的函数处理后的返回值。例如:
const a = [1, 2, 3];
const b = a.map(x => x * 2);
console.log(b)//[2,4,6]
Array.map()参数
- callback: 生成新数组元素的处理函数,接收三个参数:
- currentValue:数组中正在处理的当前元素。
- index(可选):数组中正在处理的当前元素的索引。
- array(可选):map方法调用的数组。
- thisArg(可选): 执行callback函数时值被用作this
Array.map()具体实现
Array.prototype.myMap = function (fn, thisValue) {
const res = [];
thisValue = thisValue || [];
const 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((item) => {
return item * 2;
});
console.log(b);//[ 2, 4, 6 ]
使用reduce重写Array.map()
Array.prototype.myMap = function (fn, thisValue){
const res = []
thisValue = thisValue || []
let arr = this
arr.reduce((pre, cur, index, arr) => {
res.push(fn.call(thisValue, cur, index, arr))
}, [])
return res
}