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('map' 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 === 'function') { 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!