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