js实现 map
实现 map 方法
在 JavaScript 中,map 是一个高阶函数,用于对数组中的每个元素执行指定的操作,并返回一个新数组。以下是几种实现 map 的方法。
使用原生 Array.prototype.map
原生 map 方法是最直接的实现方式:

const array = [1, 2, 3];
const mappedArray = array.map((item) => item * 2);
console.log(mappedArray); // [2, 4, 6]
手动实现 map
可以通过手动实现 map 方法来理解其工作原理:

function customMap(arr, callback) {
const result = [];
for (let i = 0; i < arr.length; i++) {
result.push(callback(arr[i], i, arr));
}
return result;
}
const array = [1, 2, 3];
const mappedArray = customMap(array, (item) => item * 2);
console.log(mappedArray); // [2, 4, 6]
使用 reduce 实现 map
reduce 方法也可以用来实现 map:
function mapWithReduce(arr, callback) {
return arr.reduce((acc, current, index, array) => {
acc.push(callback(current, index, array));
return acc;
}, []);
}
const array = [1, 2, 3];
const mappedArray = mapWithReduce(array, (item) => item * 2);
console.log(mappedArray); // [2, 4, 6]
支持链式调用
如果需要支持链式调用,可以扩展 Array 原型:
Array.prototype.customMap = function(callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
};
const array = [1, 2, 3];
const mappedArray = array.customMap((item) => item * 2);
console.log(mappedArray); // [2, 4, 6]
注意事项
map方法不会改变原数组,而是返回一个新数组。- 回调函数接收三个参数:当前元素、当前索引和原数组。
- 如果需要在稀疏数组上使用
map,空位会被跳过。






