Home >Web Front-end >JS Tutorial >map and forEach are compatible with ie6-8 methods

map and forEach are compatible with ie6-8 methods

小云云
小云云Original
2018-03-07 14:09:241746browse

This article mainly shares with you how map and forEach are compatible with ie6-8. It is mainly explained in the form of code. I hope it can help everyone.

/**
* forEach遍历数组
* @param callback [function] 回调函数;
* @param context [object] 上下文;
*/
Array.prototype.myForEach = function myForEach(callback,context){
  context = context || window;
  if('forEach' in Array.prototye) {
    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);
  }
}
/**
* map遍历数组
* @param callback [function] 回调函数;
* @param context [object] 上下文;
*/
Array.prototype.myMap = function myMap(callback,context){
  context = context || window;
  if(&#39;map&#39; in Array.prototye) {
    return this.map(callback,context);
  }
  //IE6-8下自己编写回调函数执行的逻辑
  var newAry = [];
  for(var i = 0,len = this.length; i < len;i++) {
    if(typeof callback === &#39;function&#39;) {
      var val = callback.call(context,this[i],i,this);
      newAry[newAry.length] = val;
    }
  }
  return newAry;
}

Related recommendations:

Detailed explanation of forEach, $.each and map methods in JavaScript

The above is the detailed content of map and forEach are compatible with ie6-8 methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Closures in JavaScriptNext article:Closures in JavaScript