一 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;
};