Skip to content

实现 Array.prototype.forEach()

Posted on:2021年7月7日 at 00:12
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++;
  }
};
原文转自:https://fe.ecool.fun/topic/f1974383-8f98-4cd9-8a8e-f0c51e61b275