JS數組的forEach方法(兼容所有瀏覽器)


 
        
//->自己在內置類的原型上擴展一個myForEach來處理forEach不兼容的問題
//callBack:回調函數,遍歷數組中的一項,就要執行一次callBack
//context:改變callBack方法中的this指向

Array.prototype.myForEach = function myForEach(callBack, context) {

typeof context === "undefined" ? context = window : null;

if ("forEach" in Array.prototype) {
this.forEach(callBack, context);
return;
}

//->不兼容處理
for (var i = 0; i < this.length; i++) {
typeof callBack === "function" ? callBack.call(context, this[i], i, this) : null;
}
};




 
        
 


免責聲明!

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



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