实现map js
实现 JavaScript 的 map 方法
在 JavaScript 中,map 是一个常用的数组方法,用于对数组中的每个元素执行指定的操作,并返回一个新的数组。以下是几种实现方式:
使用原生 Array.prototype.map
原生 map 方法是最直接的方式:
const array = [1, 2, 3, 4];
const mappedArray = array.map(item => item * 2);
console.log(mappedArray); // [2, 4, 6, 8]
自定义实现 map 方法
可以通过自定义函数模拟 map 的功能:
function customMap(array, callback) {
const result = [];
for (let i = 0; i < array.length; i++) {
result.push(callback(array[i], i, array));
}
return result;
}
const array = [1, 2, 3, 4];
const mappedArray = customMap(array, item => item * 2);
console.log(mappedArray); // [2, 4, 6, 8]
在原型链上扩展 map 方法
可以为数组的原型链添加自定义的 map 方法:
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, 4];
const mappedArray = array.customMap(item => item * 2);
console.log(mappedArray); // [2, 4, 6, 8]
使用 reduce 实现 map
reduce 方法也可以用来实现 map 的功能:
function mapWithReduce(array, callback) {
return array.reduce((acc, current, index, arr) => {
acc.push(callback(current, index, arr));
return acc;
}, []);
}
const array = [1, 2, 3, 4];
const mappedArray = mapWithReduce(array, item => item * 2);
console.log(mappedArray); // [2, 4, 6, 8]
注意事项
- 回调函数的参数顺序为
(currentValue, index, array)。 map方法不会修改原数组,而是返回一个新数组。- 如果需要在稀疏数组上使用
map,自定义实现时需注意处理未定义的项。







