0
点赞
收藏
分享

微信扫一扫

JS自定义数组方法(简单运算类)

一、自定义forEach

Array.prototype.myForEach = function(callback) {
    for(let i=0;i<this.length;i++){
        callback(this[i],i,this)
   }
}
const arr1=[1,2,3]
arr1.myForEach((item, index,data)=>{
  console.log(item)
  console.log(index)
  console.log(data); 
})

二、自定义map方法

Array.prototype.myMap = function(callback) {
    const arr=[]
    for(let i=0;i<this.length;i++){
        const  res=callback(this[i],i,this)
        arr.push(res)
   }
   return arr
}
const arr1=[1,2,3]
const arr2=arr1.myMap((item, index,data)=>{
  console.log(item)
  console.log(index)
  console.log(data); 
  return item+'hhhhhhh'
})
console.log(arr2);

三、自定义filter方法

Array.prototype.myFilter = function(callback) {
    const arr=[]
    for(let i=0;i<this.length;i++){
        const  res=callback(this[i],i,this)
        if(res){
            arr.push(this[i])
        }
   }
   return arr
}
const arr1=[1,2,3]
const arr2=arr1.myFilter((item, index,data)=>item!==3)
console.log(arr2);

四、自定义reduce方法

Array.prototype.myReduce = function(callback,total) {
    for(let i=0;i<this.length;i++){
        const res=callback(total,this[i],i)
        total=res
   }
   return total
}
const arr1=[1,6,3]
const arr2=arr1.myReduce((prev, cur,index)=>{
    return prev+cur
},0)
console.log(arr2);

五、自定义every方法

Array.prototype.myEvery = function(callback) {
    for(let i=0;i<this.length;i++){
        const res=callback(this[i],i,this)
        if(!res){
            return false
        }
   }
   return true
}
const arr1=[1,6,3]
const arr2=arr1.myEvery((curr,index,arr)=>{
    return index>0
})
console.log(arr2);
举报

相关推荐

0 条评论