如何用原生实现forEach

277 阅读1分钟

最近在刷leetcode,想用foreach遍历,发现怎么用结果返回都不是我想要的。我火速查了一下foreach原理,彻底弄明白了foreach机制,foreach是不能跳出循环的。

Array.prototype._forEach = function(fn) {
  // 实现一个 forEach 方法
    for(let i = 0; i < this.length; i++) {
      fn(this[i], i, this); // 调用的时候fn.call(it,i,this) fn全局变量
  }
};