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, 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); }};
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun測試上述代碼運行效果。
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript數學運算用法總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript數組操作技巧總結》、《JavaScript排序算法總結》、《JavaScript遍歷算法與技巧總結》、《JavaScript查找算法技巧總結》及《JavaScript錯誤與調試技巧總結》
希望本文所述對大家JavaScript程序設計有所幫助。
相關文章:
1. Spring-Richclient 0.1.0 發布2. Express 框架中使用 EJS 模板引擎并結合 silly-datetime 庫進行日期格式化的實現方法3. IntelliJ IDEA設置條件斷點的方法步驟4. IIS Express 取代 ASP.NET Development Server的配置方法5. IntelliJ Idea2017如何修改緩存文件的路徑6. Python使用oslo.vmware管理ESXI虛擬機的示例參考7. Java構建JDBC應用程序的實例操作8. Intellij IDEA 旗艦版創建 Spring MVC 項目踩過的坑9. Jsp中request的3個基礎實踐10. 一篇文章帶你了解JavaScript-對象
