JS實(shí)現(xiàn)手寫(xiě) forEach算法示例
本文實(shí)例講述了JS實(shí)現(xiàn)手寫(xiě) forEach算法。分享給大家供大家參考,具體如下:
手寫(xiě) forEach
forEach()方法對(duì)數(shù)組的每個(gè)元素執(zhí)行一次提供的函數(shù)
arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);
callback
currentValue 數(shù)組中正在處理的當(dāng)前元素。 index 可選 數(shù)組中正在處理的當(dāng)前元素的索引。 array 可選 forEach() 方法正在操作的數(shù)組。 thisArg 可選 可選參數(shù)。當(dāng)執(zhí)行回調(diào)函數(shù) callback 時(shí),用作 this 的值。 沒(méi)有返回值如果提供了一個(gè) thisArg 參數(shù)給 forEach 函數(shù),則參數(shù)將會(huì)作為回調(diào)函數(shù)中的 this 值。否則 this 值為 undefined。回調(diào)函數(shù)中 this 的綁定是根據(jù)函數(shù)被調(diào)用時(shí)通用的 this 綁定規(guī)則來(lái)決定的。
let arr = [1, 2, 3, 4];arr.forEach((...item) => console.log(item));// [1, 0, Array(4)] 當(dāng)前值
function Counter() { this.sum = 0; this.count = 0;}// 因?yàn)?thisArg 參數(shù)(this)傳給了 forEach(),每次調(diào)用時(shí),它都被傳給 callback 函數(shù),作為它的 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) 每個(gè)數(shù)組都有這個(gè)方法 回調(diào)參數(shù)為:每一項(xiàng)、索引、原數(shù)組
Array.prototype.forEach = function(fn, thisArg) { var _this; if (typeof fn !== 'function') { throw '參數(shù)必須為函數(shù)'; } if (arguments.length > 1) { _this = thisArg; } if (!Array.isArray(arr)) { throw '只能對(duì)數(shù)組使用forEach方法'; } for (let index = 0; index < arr.length; index++) { fn.call(_this, arr[index], index, arr); }};
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運(yùn)行工具:http://tools.jb51.net/code/HtmlJsRun測(cè)試上述代碼運(yùn)行效果。
更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript數(shù)組操作技巧總結(jié)》、《JavaScript排序算法總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》、《JavaScript查找算法技巧總結(jié)》及《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》
希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。
相關(guān)文章:
1. java——Byte類(lèi)/包裝類(lèi)的使用說(shuō)明2. android studio實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器(無(wú)bug)3. python 讀txt文件,按‘,’分割每行數(shù)據(jù)操作4. python Selenium 庫(kù)的使用技巧5. android 控件同時(shí)監(jiān)聽(tīng)單擊和雙擊實(shí)例6. python+pywinauto+lackey實(shí)現(xiàn)PC端exe自動(dòng)化的示例代碼7. vue使用exif獲取圖片經(jīng)緯度的示例代碼8. python logging.info在終端沒(méi)輸出的解決9. 詳解android adb常見(jiàn)用法10. Python 忽略文件名編碼的方法
