歡迎您光臨本站 註冊首頁

JS實現手寫 forEach算法示例

←手機掃碼閱讀     e36605 @ 2020-05-05 , reply:0

本文實例講述了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); } };


[e36605 ] JS實現手寫 forEach算法示例已經有261次圍觀

http://coctec.com/docs/javascript/show-post-232914.html