js 实现 map
实现自定义 map 方法
在 JavaScript 中实现类似原生 Array.prototype.map 的功能,可以通过以下方式完成:
function customMap(array, callback) {
const result = [];
for (let i = 0; i < array.length; i++) {
result.push(callback(array[i], i, array));
}
return result;
}
作为 Array 原型方法实现
也可以将其添加到 Array 的原型上,使其可以像原生 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;
};
使用方法示例
const numbers = [1, 2, 3, 4];
// 使用自定义 map 函数
const doubled = customMap(numbers, num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
// 使用原型方法
const tripled = numbers.myMap(num => num * 3);
console.log(tripled); // [3, 6, 9, 12]
实现注意事项
自定义 map 方法应包含以下特性:
- 接收一个回调函数作为参数
- 回调函数接收当前元素、索引和原数组三个参数
- 返回一个新数组,不修改原数组
- 保持原数组的稀疏性(跳过未定义的元素)
更完整的实现
Array.prototype.myMap = function(callback, thisArg) {
if (this == null) {
throw new TypeError('Array.prototype.myMap called on null or undefined');
}
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
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;
};
这个实现更接近原生 map 方法的行为,包括类型检查、稀疏数组处理和 thisArg 参数支持。







