You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
thisArg 可选:对象作为该执行回调时使用,传递给函数,用作 "this" 的值。如果省略了 thisArg,或者传入 null、undefined,那么回调函数的 this 为全局对象。
参考实现
Array.prototype.myMap=function(fn,thisArg=[]){if(typeoffn!==function){thrownewError(`${fn} is not a function`);}returnthis.reduce((pre,cur,index,arr)=>{returnpre.concat(fn.call(thisArg,cur,index,arr));},[]);};vararr=[2,3,1,5];arr.myMap(function(item,index,arr){console.log(item,index,arr);});letres=arr.myMap((v)=>v*2);console.log(res);// [4,6,2,10]
The text was updated successfully, but these errors were encountered:
扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。
reduce & map
reduce 是一个累加方法,是对数组累积执行回调函数,返回最终计算的结果。
map 是遍历数组的每一项,并执行回调函数的操作,返回一个对每一项进行操作后的新数组。
currentValue 必需:当前元素只
index 可选:当前元素索引值
arr 可选:当前元素所属数组对象
thisArg 可选:对象作为该执行回调时使用,传递给函数,用作 "this" 的值。如果省略了 thisArg,或者传入 null、undefined,那么回调函数的 this 为全局对象。
参考实现
The text was updated successfully, but these errors were encountered: