js map 实现
map 方法的基本原理
map 是 JavaScript 数组的高阶函数,用于对数组每个元素执行回调函数并返回新数组。其核心特点是不修改原数组,而是通过映射关系生成新数组。
原生 map 用法示例
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // 输出: [2, 4, 6]
手动实现 map 的步骤
定义函数框架
创建一个接受回调函数和可选 thisArg 的函数:

function customMap(callback, thisArg) {
const result = [];
// 后续逻辑填充
return result;
}
遍历原数组
使用 for 循环遍历数组的每个元素:
for (let i = 0; i < this.length; i++) {
// 处理每个元素
}
执行回调并收集结果
对每个元素调用回调函数,并将结果存入新数组:

const mappedValue = callback.call(thisArg, this[i], i, this);
result.push(mappedValue);
完整实现代码
Array.prototype.customMap = function(callback, thisArg) {
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
const result = [];
for (let i = 0; i < this.length; i++) {
const mappedValue = callback.call(thisArg, this[i], i, this);
result.push(mappedValue);
}
return result;
};
// 使用示例
const arr = [1, 2, 3];
const squared = arr.customMap(x => x * x);
console.log(squared); // 输出: [1, 4, 9]
关键实现细节
- 类型检查:确保回调是函数类型
- 参数传递:正确处理
thisArg绑定 - 索引传递:提供当前索引和原数组引用
- 稀疏数组:原生
map会跳过空位,此处简化实现
边界情况处理
处理稀疏数组
如需完全模拟原生行为,需增加空位检测:
if (!(i in this)) {
result.length++; // 保持稀疏性
continue;
}
链式调用支持
返回的数组可继续调用其他数组方法:
[1, 2, 3]
.customMap(x => x + 1)
.filter(x => x > 2); // 输出: [3, 4]
性能优化建议
- 提前分配数组长度:
const result = new Array(this.length); - 避免不必要的类型检查(生产环境可移除)






