Home > Web Front-end > JS Tutorial > body text

map and forEach are compatible with ie6-8 methods

小云云
Release: 2018-03-07 14:09:24
Original
1661 people have browsed it

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!