Array.prototype.forEach=function(callback, context){// 不能是null调用方法if(this===null){thrownewTypeError("Array.prototype.forEach"+"called on null or undefined");}// 第一个参数必须要为functionif(typeof callback !=="function"){thrownewTypeError(callback +" is not a function");}// 获取原数组,因为会改变原数组let arr =this;let len = arr.length;//for(let i =0; i < len; i++){callback.call(context, arr[i], i, arr);}// 数组没有返回值的,不用返回}
map实现:
Array.prototype.map=function(callback, context){// 不能是null调用方法if(this===null){thrownewTypeError("Array.prototype.map"+"called on null or undefined");}// 第一个参数必须要为functionif(typeof callback !='function'){thrownewTypeError(
callback +'is not a function')}// 利用slice方法浅拷贝一下let arr =Array.prototype.slice.call(this)let len = arr.length
let arrMap =[]for(let i =0; i < len; i++){
arrMap[i]=callback.call(context, arr[i], i, arr)}return arrMap
}