const array = [1, 2, 3, 4, 5, 6, 7, 8];
// 第一个参数是 函数
// 第二个参数是 this 的指向 (可选)
Array.prototype._map = function(callback, thisArg = window){
// 第一个参数不是一个函数的话, 抛出异常
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
let arr = [];
const len = this.length;
for (let i = 0; i < len; i++) {
// 将处理后的数据 push 到新的数组中
arr.push(callback.apply(thisArg, [this[i], i, this]));
}
return arr;
}
/**
* @param item 当前正在处理的数组元素的值。
* @param index 当前正在处理的数组元素的索引。(可选)
* @param arr 正在遍历的数组本身。(可选):
* @returns {Object} 返回函数处理后的值
*/
function handleArr(item, index, arr) {
console.log(this); // 这里的 this 指向的是 obj
return item * 2; // 所有数据 乘 2
}
const obj = {name: '张三'};
const arr = array._map(handleArr, obj);
console.log(arr, 'arr///'); // [2, 4, 6, 8, 10, 12, 14, 16]
JavaScrip 之 手写 map
最新推荐文章于 2024-07-29 11:53:27 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)