语法:

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

参数:

*callback*

为数组中每个元素执行的函数,该函数接收一至三个参数:

*currentValue*

数组中正在处理的当前元素。

*index* 可选

数组中正在处理的当前元素的索引。

*array* 可选

forEach() 方法正在操作的数组。

*thisArg* 可选

可选参数。当执行回调函数 *callback* 时,用作 this 的值。

返回值:

undefined

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

实现:

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++;
  }
}