js 实现 map
实现 JavaScript 的 map 方法
基本实现原理
map 方法创建一个新数组,其结果是原数组每个元素调用一次提供的函数后的返回值。核心逻辑是遍历原数组,对每个元素执行回调函数,并将结果存入新数组。
Array.prototype.myMap = function(callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
};
完整实现(包含 thisArg 参数)
原生 map 方法支持第二个参数 thisArg,用于指定回调函数的 this 值。

Array.prototype.myMap = function(callback, thisArg) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback.call(thisArg, this[i], i, this));
}
return result;
};
使用示例
测试自定义实现的 map 方法:

const arr = [1, 2, 3];
const doubled = arr.myMap(item => item * 2);
console.log(doubled); // [2, 4, 6]
边界情况处理
处理稀疏数组(存在 empty 元素)的情况:
Array.prototype.myMap = function(callback, thisArg) {
const result = new Array(this.length);
for (let i = 0; i < this.length; i++) {
if (i in this) {
result[i] = callback.call(thisArg, this[i], i, this);
}
}
return result;
};
性能优化
避免在每次迭代中重复计算数组长度:
Array.prototype.myMap = function(callback, thisArg) {
const result = new Array(this.length);
const len = this.length;
for (let i = 0; i < len; i++) {
if (i in this) {
result[i] = callback.call(thisArg, this[i], i, this);
}
}
return result;
};






