map重写
Array.prototype.map_2=function(fn){
let list=[]
let arr=this
for(let i=0;i<arr.length;i++){
let res=fn(arr[i],i,arr)
list.push(res)
}
return list
}
let arr=[1,2,3,4]
let a=arr.map_2((item,index,array)=>{
console.log(item);
console.log(index);
console.log(array);
})
console.log(a)
reduce重写
Array.prototype.my_reduce=function(callback,prev){
if(!Array.isArray(this)){
throw new Error('这是数组的方法!')
}
if(typeof callback!=='function'){
throw new Error('callback must be an function!')
}
let i=prev?0:1
prev=prev||this[0]
for(i;i<this.length;i++){
prev=callback(prev,this[i],i,this)
}
return prev
}
var arr=[1,2,3,4,5]
var a=arr.my_reduce((sum,item)=>{
return sum+item
},10)
console.log(a);