簡體   English   中英

函數式編程:在原型上實現 map 通過 JavaScript

[英]Functional Programming: Implement map on a PrototypePassed JavaScript

我正在做 FreeCodeCamp 的練習,但我沒有得到邏輯和代碼。 就這個:

// the global Array
var s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback) {
  var newArray = [];
  // Add your code below this line
  this.forEach(a => newArray.push(callback(a)));
  // Add your code above this line
  return newArray;
};

var new_s = s.myMap(function(item) {
  return item * 2;
});

誰能幫我解釋一下? 謝謝!

此代碼將 output 到new_s一個包含s x 2 值的數組

讓我們回顧一下:

Array.prototype.myMap = function(callback) { ... }
  • myMap是適用於 arrays ( Array.prototype ) 的 function
  • 這個 function 有一個名為callback的參數。 這個參數將是一個 function(即使在這里你仍然只能從參數的名稱中猜測;)
  var newArray = [];
  // Add your code below this line
  this.forEach(a => newArray.push(callback(a)));
  // Add your code above this line
  return newArray;
  • 循環遍歷this的所有值(您將應用myMap的數組)
  • callback引用的 function 應用於每個值
  • callback function 的結果添加到newArray數組中
  • 返回結果數組

最后:

var new_s = s.myMap(function(item) {
  return item * 2;
});
  • 應用myMap function 到s callback function 是一個 function 將返回,值為s2 * s

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM