鍍金池/ 問答/HTML/ 如何用原生JS實現(xiàn)一個forEach?

如何用原生JS實現(xiàn)一個forEach?

Array.prototype._forEach = function(fn) {
  // 怎么實現(xiàn)一個 forEach 方法?
};

function Person(age) {
  this.age = age;
  [3,5,10]._forEach(function(it){
      console.log(`${it} year later I'm ${this.age + it} year old`);
  });
}

let mike = new Person(12);
// 3 year later I'm 15 year old
// 5 year later I'm 17 year old
// 10 year later I'm 22 year old
回答
編輯回答
慢半拍
2017年4月24日 05:48
編輯回答
萌面人

你的問題應該是, 如何使用 ES3 實現(xiàn) ES5 Array 的 forEach 方法?

Array.prototype._forEach = function(fn) {
    for (var i=0; i<this.length; i++) {
        fn(this[i])
    }
};
2017年2月25日 23:56
編輯回答
傲寒
Array.prototype._forEach = function(fn) {
  // 實現(xiàn)一個 forEach 方法
    for(let i = 0; i < this.length; i++) {
      let it = this[i];
      fn(it, i, this); // 看這里,調(diào)用的時候是這樣的 fn.call(it,i,this) fn 沒有綁定任何的上下文,所以是全局變量
  }
};
2017年9月21日 10:59