溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

JS如何實現手寫forEach算法

發布時間:2020-07-29 13:46:43 來源:億速云 閱讀:399 作者:小豬 欄目:web開發

小編這次要給大家分享的是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, 0, 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);
 }
};

看完這篇關于JS如何實現手寫forEach算法的文章,如果覺得文章內容寫得不錯的話,可以把它分享出去給更多人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女