1. 程式人生 > 程式設計 >JS實現手寫 forEach演算法示例

JS實現手寫 forEach演算法示例

本文例項講述了JS實現手寫 forEach演算法。分享給大家供大家參考,具體如下:

手寫 forEach

forEach()方法對陣列的每個元素執行一次提供的函式

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

  • callback

    • currentValue
      陣列中正在處理的當前元素。
    • index 可選
      陣列中正在處理的當前元素的索引。
    • array 可選
      forEach() 方法正在操作的陣列。
    • thisArg 可選
      可選引數。當執行回撥函式 callback 時,用作 this 的值。
  • 沒有返回值

如果提供了一個 thisArg 引數給 forEach 函式,則引數將會作為回撥函式中的 this 值。否則 this 值為 undefined。回撥函式中 this 的繫結是根據函式被呼叫時通用的 this 繫結規則來決定的。

let arr = [1,2,3,4];

arr.forEach((...item) => console.log(item));

// [1,Array(4)] 當前值

function Counter() {
 this.sum = 0;
 this.count = 0;
}

// 因為 thisArg 引數(this)傳給了 forEach(),每次呼叫時,它都被傳給 callback 函式,作為它的 this 值。
Counter.prototype.add = function(array) {
 array.forEach(function(entry) {
  this.sum += entry;
  ++this.count;
 },this);
 // ^---- Note
};

const obj = new Counter();
obj.add([2,5,9]);
obj.count;
// 3 === (1 + 1 + 1)
obj.sum;
// 16 === (2 + 5 + 9)

  • 每個陣列都有這個方法
  • 回撥引數為:每一項、索引、原陣列
Array.prototype.forEach = function(fn,thisArg) {
 var _this;
 if (typeof fn !== "function") {
  throw "引數必須為函式";
 }
 if (arguments.length > 1) {
  _this = thisArg;
 }
 if (!Array.isArray(arr)) {
  throw "只能對陣列使用forEach方法";
 }

 for (let index = 0; index < arr.length; index++) {
  fn.call(_this,arr[index],index,arr);
 }
};

感興趣的朋友可以使用線上HTML/CSS/JavaScript程式碼執行工具:http://tools.jb51.net/code/HtmlJsRun測試上述程式碼執行效果。

更多關於JavaScript相關內容感興趣的讀者可檢視本站專題:《JavaScript數學運算用法總結》、《JavaScript資料結構與演算法技巧總結》、《JavaScript陣列操作技巧總結》、《JavaScript排序演算法總結》、《JavaScript遍歷演算法與技巧總結》、《JavaScript查詢演算法技巧總結》及《JavaScript錯誤與除錯技巧總結》

希望本文所述對大家JavaScript程式設計有所幫助。