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;
}
};





 
posted @ 2016-01-27 21:38  __sarah  Views(9887)  Comments(0Edit  收藏  举报