题解 | #Array.map#
Array.map
https://www.nowcoder.com/practice/8300c998180c4ebbbd2a5aaeb7fbc77c
Array.prototype._map = function (Fn) {
const that = this; // 传入的数组
const ansArr = []; // 新建一个存储数组
// 使用 forEach 进行遍历,因为 Fn 会传三个属性 值:item,索引:index,原数组:element,不能使用forof
that.forEach((item,index,element)=>{
// 传入参数并且进行 Fn 操作,将每次返回的结果赋值给 resElement;
const resElement = Fn(item,index,element);
ansArr.push(resElement); // push 进数组
})
return ansArr;
}
// 定义一个 Fn
function fn(item) {
return item * 2
}
// 定义一个数组
const arr = [1, 2];
// 正常 map 返回的结果
const testArr = arr.map(item => {
return item * 2
})
console.log(testArr); // [2,4]
// 模拟 _map 返回的结果
console.log(arr._map(fn)); //[2,4]
顺丰集团工作强度 289人发布