ie8以下 es5常见的数组遍历方法不可用的解决方案 forEach,map,filter,some,every

为了兼容ie8以下的写法

1.forEach

Array.prototype.myForEach = function (callback,context){
  context = context || window;
  if(Array.prototype.forEach) {
      this.forEach(callback,context);
      return;
  }
  //IE6-8下自己编写回调函数执行的逻辑
  for(var i = 0,len = this.length; i < len;i++) {
      callback && callback.call(context,this[i],i,this);
  }
}
var qq = [1,2,3,4,5]
qq.myForEach(function(item,index,arr){
  
  arr[index]+=1
})
console.log(qq)


2.map

Array.prototype.mymap = function (callback,context){
  //判断是否为ie8以下
  context = context || window;//是否有this指向
  if(Array.prototype.map){
    
    return this.map(callback,window);
  }
  var newArry=[]
  for (var i=0;i<this.length;i++){
     var val=  callback.call(context,this[i],i,this)
       
       newArry[i]=val;
  }
  return newArry
}
var qq = [1,2,3,4,5]
var arr1= qq.mymap(function(item,index,arr){
   return item+1
})
console.log(arr1)

3.filter

Array.prototype.myfilter = function (callback,context){
  //判断是否为ie8以下
  context = context || window;//是否有this指向
  if(Array.prototype.map){
    
    return this.map(callback,window);
  }
  var newArry=[]
  for (var i=0;i<this.length;i++){
     var val=  callback.call(context,this[i],i,this)
      
      if(val){
        newArry.push(this[i])
      }
  }
  return newArry
}
var qq = [1,2,3,4,5]
var arr1= qq.myfilter(function(item,index,arr){
   return item>=2
})
console.log(arr1)


4.some

Array.prototype.mysome = function (callback,context){
  //判断是否为ie8以下
  context = context || window;//是否有this指向
  if(Array.prototype.map){
    
    return this.some(callback,window);
  }

  for (var i=0;i<this.length;i++){
     var val=  callback.call(context,this[i],i,this)
      if(val){
        return true;
      }
  }
  return false;
}
var qq = [1,2,3,4,5]
var arr1= qq.mysome(function(item,index,arr){
   return item>=2
})
console.log(arr1)

5.every

Array.prototype.myevery = function (callback,context){
  //判断是否为ie8以下
  context = context || window;//是否有this指向
  if(Array.prototype.map){
    
    return this.every(callback,window);
  }

  for (var i=0;i<this.length;i++){
     var val=  callback.call(context,this[i],i,this)
      if(!val){
        return false;
      }
  }
  return true;
}
var qq = [1,2,3,4,5]
var arr1= qq.myevery(function(item,index,arr){
   return item>=1
})
console.log(arr1)

posted @ 2017-10-26 20:38  陈奭  阅读(241)  评论(0编辑  收藏  举报