【前端面试:手写js系列】数组的map方法和forEach方法
2021-08-20 本文已影响0人
冬天都会过去
- Array.prototype.map()

let arr = [3, 4, 5, 6, 7];
Array.prototype.mapArray = function ( fn, thisArgs ){
//处理数组类型异常
if (this === null || this === undefined){
throw new TypeError("Cannot read property 'map' of null or undefined ");
}
//处理回调函数异常
if (object.prototype.toString.call(fn) !== "[object Function]") {
throw new TypeError(fn + 'is not a function')
}
let resArray = [ ];
let curArray = Object(this);
let len = curArray.length >>> 0;
for (let i = 0; i < curArray.length; i++){
if (i in curArray){
resArray[ i ] = fn.call(thisArgs, curArray[ i ], i, curArray);
}
}
return resArray;
}
console.log(arr.mapArray((item, index, arr) => {return item + 1}));
//[4, 5, 6, 7, 8]
- Array.prototype.forEach()
forEach方法和map方法类似,唯一不同的是forEach没有返回值。

//forEach方法和map方法类似,唯一不同的是forEach没有返回值
Array.prototype.forEach = function(callback, thisArgs){
if( this === null || this === undefined){
throw new TypeError("this is null or not defined");
}
if( object.prototype.toString.call(callback) !== "[object function]"){
throw new TypeError(callback+"is not a function");
}
let curArr = Object(this);
let len = curArr.length >>> 0;
let i = 0;
while( i < len){
if (i in curArr){
callback.call(thisArgs, curArr[i], i, curArr);
}
i++;
}
}