Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array.prototype.forEach #10

Open
Sunny-117 opened this issue Nov 3, 2022 · 3 comments
Open

Array.prototype.forEach #10

Sunny-117 opened this issue Nov 3, 2022 · 3 comments

Comments

@Sunny-117
Copy link
Owner

// 无返回值,调用callback
Array.prototype.myForEach = function (callback) {
  if (typeof callback !== "function") {
    throw new TypeError(callback + " is not a function");
  }
  for (let i = 0; i < this.length; i++) {
    callback(this[i], i, this);
  }
};
@CwRv07
Copy link
Contributor

CwRv07 commented Nov 4, 2022

Array.prototype._forEach = function (cb, thisBinding = globalThis) {
  // 排除回调非函数情况
  if (typeof cb !== "function") {
    throw new TypeError(`${cb} is not a function`);
  }
  // 排除this为非可迭代对象情况
  if (this == null || typeof this[Symbol.iterator] !== "function") {
    throw new TypeError(`${this} is not a iterable`);
  }
  // 将可迭代对象转换成数组
  const array = [...this];
  // 执行遍历并回调
  for (let i = 0; i < array.length; i++) {
    cb.call(thisBinding, array[i], i, this);
  }
};

@hannah-bingo
Copy link
Contributor

forEach和map类似,但是forEach不返回结果

Array.prototype._forEach = function(callback, objThis) {
	if(typeof callback !== "function") {
		throw new TypeError("callback type error!")
	}
	for(let i = 0; i < this.length; i++) {
		callback.call(objThis, this[i], i, this);
	}	
}

@kangkang123269
Copy link

kangkang123269 commented Feb 20, 2023

Array.prototype.myForEach = function(callback, thisArg) {
  if (this == null) {
    throw new TypeError("Cannot read property 'forEach' of null or undefined");
  }
  if (typeof callbackFn !== 'function') {
    throw new TypeError(callbackFn + ' is not a function');
  }
  for (let i = 0; i < this.length; i++) {
    callback.call(thisArg, this[i], i, this);
  }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants