Skip to content

数组-手写forEach

forEachmap 类似,唯一不同的是 forEach 是没有返回值的。

polyfill

js
Array.prototype.forEach = function(callback, thisArg) {
  if (this == null) {
    throw new TypeError('this is null or not defined');
  }
  if (typeof callback !== "function") {
    throw new TypeError(callback + ' is not a function');
  }
  const O = Object(this);
  const len = O.length >>> 0;
  let k = 0;
  while (k < len) {
    if (k in O) {
      callback.call(thisArg, O[k], k, O);
    }
    k++;
  }
}

MIT Licensed | 沪ICP备20013265号-1 | Copyright © 2019-present AaronKong