数组方法polyfill已经烂大街了,且mdn就有相关源码。重要是我理解思路,手到擒来了😊
forEach
Array.prototype.MyForEach = function(cb, thisArg) {
//数组实例null, undefined判断。如果用 === ,就不能拦截undefined
if(this == null) {
throw new Error('this is null or not defined')
}
//回调函数判断
if(typeof cb !== 'function') {
throw new TypeError(cb + ' is not a function')
}
//保证操作不改变当前的数组实例
var O = Object(this);
//cb内部this的改变
var T = thisArg ? thisArg : null;
//数组长度
var len = O.length;
//计数器
var k = 0;
while(k < len) {
if(k in O) {
cb.call(T, O[k], k);
}
k++;
}
}