数组方法polyfill已经烂大街了,且mdn就有相关源码。重要是我理解思路,手到擒来了😊
forEach
Array.prototype.MyForEach = function(cb, thisArg) {//数组实例null, undefined判断。如果用 === ,就不能拦截undefinedif(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++;}}
