forEach

# forEach

Array.prototype.myForEach = function (callback, thisArg) {
  // this 指向当前数组
  const array = this
  console.log('>>>this', this) //[1, 2, 3, 4]
  // 检查回调函数是不是函数
  if (typeof callback !== 'function') {
    throw new TypeError(callback + ' is not a function')
  }
  // 遍历数组的每个元素
  for (let i = 0; i < array.length; i++) {
    // 回调函数参数:当前元素,当前索引,原数组
    // 如果提供了 thisArg 参数,则将其作为回调函数的 this 值,否则默认为 undefined
    callback.call(thisArg, array[i], i, array)
  }
}

let a = [1, 2, 3, 4]
a.myForEach((item, index) => {
  console.log(item, index)
})

注意事项 为什么 forEach 中不能 return?

这个回调函数由你提供,并在 forEach 的每次迭代过程中被调用。 在 forEach 的回调函数中,使用 return 确实会退出当前正在执行的回调函数,但它并不能退出 forEach 循环本身。