数组方法polyfill已经烂大街了,且mdn就有相关源码。重要是我理解思路,手到擒来了😊

forEach

  1. Array.prototype.MyForEach = function(cb, thisArg) {
  2. //数组实例null, undefined判断。如果用 === ,就不能拦截undefined
  3. if(this == null) {
  4. throw new Error('this is null or not defined')
  5. }
  6. //回调函数判断
  7. if(typeof cb !== 'function') {
  8. throw new TypeError(cb + ' is not a function')
  9. }
  10. //保证操作不改变当前的数组实例
  11. var O = Object(this);
  12. //cb内部this的改变
  13. var T = thisArg ? thisArg : null;
  14. //数组长度
  15. var len = O.length;
  16. //计数器
  17. var k = 0;
  18. while(k < len) {
  19. if(k in O) {
  20. cb.call(T, O[k], k);
  21. }
  22. k++;
  23. }
  24. }