js 手寫 map 函數


一 map 函數(copyMap)

map函數接收兩個參數

1 迭代器函數 ,該函數有三個參數

  • 數組項的值
  • 數組項下標
  • 數組對象本身

2 迭代器函數的this指向
(注:當傳了該值,迭代器函數不能為箭頭函數了。原因是箭頭函數沒有this隱式指向。箭頭函數在定義時候就已經綁定了上層上下文中非箭頭函數this)

Array.prototype.copyMap = function (fn, toThis) {
  let arr = this;
  const result = [];
  const redirectThis = toThis || Object.create(null);
  for (let i = 0; i < arr.length; i++) {
    const item = fn.call(redirectThis, arr[i], i, arr);
    result.push(item);
  }
  return result;
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM