// 重构js数组的map方法
Array.prototype.map=function(fn, context){if(typeof fn !='function'){thrownewTypeError(`${fn} is not a function`);}let arr =this, temp =[];for(let i =0; i < arr.length; i++){let result = fn.call(context, arr[i], i, arr);
temp.push(result);}return temp;}
2.重构js数组的forEach方法
// 重构js数组的forEach方法
Array.prototype.forEach=function(fn, context){if(typeof fn !='function'){thrownewTypeError(`${fn} is not a function`);}for(let i =0; i <this.length; i++){
fn.call(context,this[i], i,this);}returnthis;}
3.重构js数组的every方法
// 重构js数组的every方法
Array.prototype.every=function(fn, context){if(typeof fn !='function'){thrownewTypeError(`${fn} is not a function`);}for(let i =0; i < arr.length; i++){let result = fn.call(context,this[i], i,this);return!result ?false:true;}}
4.重构js数组的some方法
// 重构js数组的some方法
Array.prototype.some=function(fn, context){if(typeof fn !='function'){thrownewTypeError(`${fn} is not a function`);}for(let i =0; i <this.length; i++){let result = fn.call(context,this[i], i,this);return result ?true:false;}}
5.重构js数组的filter方法
// 重构js数组的filter方法
Array.prototype.filter=function(fn, context){if(typeof fn !='function'){thrownewTypeError(`${fn} is not a function`);}let temp =[];for(let i =0; i <this.length; i++){let result = fn.call(context,this[i], i,this);
result ? temp.push(this[i]):''}return temp;}
6.重构js数组的reduce方法
// 重构js数组的reduce方法
Array.prototype.reduce=function(fn, initialValue){if(typeof fn !='function'){thrownewTypeError(`${fn} is not a function`);}let num =0, total =null;if(initialValue !== undefined && initialValue !==null){
total = initialValue
}else{
total =this[0];
num =1;}for(let i = num; i <this.length; i++){let item =this[i];
total = fn.call(this, total, item,this);}return total;}
7.重构js数组的reduceRight方法
// 重构js数组的reduceRight方法
Array.prototype.reduceRight=function(fn, initialValue){if(typeof fn !='function'){thrownewTypeError(`${fn} is not a function`);}let length =this.length, num = length, total =null;if(initialValue !== undefined && initialValue !==null){
total = initialValue
}else{
total =this[length -1];
num = length -2;}for(let i = num; i >=0; i--){let item =this[i];
total = fn.call(this, total, item,this);}return total;}
8.重构js数组的indexOf方法
// 重构js数组的indexOf方法
Array.prototype.indexOf=function(item, start){if(!item){throwTypeError('indexOf need arguments');}for(let i = start ||0; i <this.length; i++){if(item ===this[i]){return i }}return-1;}