JavaScript:數組forEach和map的兼容處理


 IE8以下瀏覽器不兼容數組的forEach和map方法,現特做以下處理

    1、forEach的兼容處理

Array.prototype.myForEach=function(callback,context){
context=context||window;
if('forEach' in Array.prototype){
this.forEach(callback,context);
return;
}
for(var i=0; i<this.length; i++){
callback.call(context,this[i],i,this);
}
}
eg:
var ary=[12,34,56,89];
var obj={};
ary.myForEach(function(item,index,input){
input[index]=item*100;
},obj)

2、map的兼容處理
Array.prototype.myMap=function(callback,context){
context=context||window;
if('map' in Array.prototype){
return this.map(callback,context)
}
var ary=[];
for(var i=0; i<this.length; i++){
var val=callback.call(context,this[i],i,this);
ary.push(val);
}
return ary;
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM