js map 实现
实现 JavaScript 的 map 方法
JavaScript 的 map 方法是数组原型上的一个高阶函数,用于对数组的每个元素执行指定操作并返回新数组。以下是几种实现方式:
原生 Array.prototype.map 的使用示例
const arr = [1, 2, 3];
const newArr = arr.map((item) => item * 2);
console.log(newArr); // [2, 4, 6]
手动实现 map 方法(Polyfill)
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 arr = [1, 2, 3];
const doubled = arr.myMap((num) => num * 2);
console.log(doubled); // [2, 4, 6]
使用 reduce 实现 map
Array.prototype.mapViaReduce = function(callback) {
return this.reduce((acc, current, index, array) => {
acc.push(callback(current, index, array));
return acc;
}, []);
};
// 使用示例
const squares = [1, 2, 3].mapViaReduce((x) => x * x);
console.log(squares); // [1, 4, 9]
注意事项
- 回调函数接收三个参数:当前元素、当前索引、原数组。
map不会修改原数组,而是返回新数组。- 稀疏数组(含
empty项)会跳过空位,但保留空位在结果中。
性能优化建议
对于大数据量遍历,优先使用原生 map。手动实现时需注意边界条件(如 this 非数组时的处理)。







