欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS實(shí)現(xiàn)手寫 forEach算法示例

 更新時(shí)間:2020年04月29日 09:31:14   作者:xiaoping  
這篇文章主要介紹了JS實(shí)現(xiàn)手寫 forEach算法,結(jié)合實(shí)例形式分析了JS實(shí)現(xiàn)手寫 forEach算法實(shí)現(xiàn)原理與相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了JS實(shí)現(xiàn)手寫 forEach算法。分享給大家供大家參考,具體如下:

手寫 forEach

forEach()方法對數(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 的值。
  • 沒有返回值

如果提供了一個(gè) thisArg 參數(shù)給 forEach 函數(shù),則參數(shù)將會(huì)作為回調(diào)函數(shù)中的 this 值。否則 this 值為 undefined?;卣{(diào)函數(shù)中 this 的綁定是根據(jù)函數(shù)被調(diào)用時(shí)通用的 this 綁定規(guī)則來決定的。

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 "只能對數(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測試上述代碼運(yùn)行效果。

更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《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é)

希望本文所述對大家JavaScript程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論