js实现map
实现 JavaScript 的 map 方法
JavaScript 的 map 方法用于遍历数组,对每个元素执行回调函数并返回新数组。以下是自定义实现 map 的几种方式:
使用 Array.prototype 扩展
为数组原型添加自定义 myMap 方法:

Array.prototype.myMap = function(callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
};
// 使用示例
const numbers = [1, 2, 3];
const doubled = numbers.myMap(num => num * 2);
console.log(doubled); // [2, 4, 6]
独立函数实现
创建独立函数模拟 map 功能:

function map(array, callback) {
const result = [];
for (let i = 0; i < array.length; i++) {
result.push(callback(array[i], i, array));
}
return result;
}
// 使用示例
const words = ['hello', 'world'];
const lengths = map(words, word => word.length);
console.log(lengths); // [5, 5]
支持 thisArg 的实现
添加对 thisArg 参数的支持,模拟原生 map 的完整功能:
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;
};
// 使用示例
const obj = { multiplier: 3 };
const nums = [1, 2, 3];
const tripled = nums.myMap(function(num) {
return num * this.multiplier;
}, obj);
console.log(tripled); // [3, 6, 9]
使用 reduce 实现
通过 reduce 方法实现 map 功能:
Array.prototype.myMap = function(callback) {
return this.reduce((acc, current, index, array) => {
acc.push(callback(current, index, array));
return acc;
}, []);
};
// 使用示例
const chars = ['a', 'b', 'c'];
const upperChars = chars.myMap(char => char.toUpperCase());
console.log(upperChars); // ['A', 'B', 'C']
这些实现方式展示了 map 方法的核心逻辑,可以根据具体需求选择适合的方案。原生 map 方法还包含更多边界条件处理,上述示例聚焦于核心功能的演示。






