js map方法 实现
map方法的基本概念
JavaScript中的map方法是数组对象的一个高阶函数,用于对数组中的每个元素执行指定操作并返回一个新数组。原数组不会被修改。
语法结构
const newArray = array.map(function(currentValue, index, arr) {
// 返回处理后的元素
}, thisValue);
currentValue: 当前处理的数组元素index(可选): 当前元素的索引arr(可选): 正在操作的数组thisValue(可选): 执行回调时使用的this值
基本使用示例
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
实现原理
map方法的Polyfill实现可以这样理解:

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 = [];
const array = Object(this);
const len = array.length >>> 0;
for (let i = 0; i < len; i++) {
if (i in array) {
result[i] = callback.call(thisArg, array[i], i, array);
}
}
return result;
};
常见应用场景
处理对象数组提取特定属性:

const users = [
{id: 1, name: 'Alice'},
{id: 2, name: 'Bob'}
];
const names = users.map(user => user.name);
// ['Alice', 'Bob']
转换数据格式:
const temperatures = [
{city: 'Tokyo', temp: 22},
{city: 'London', temp: 14}
];
const formatted = temperatures.map(({city, temp}) =>
`${city}: ${temp}°C`
);
// ['Tokyo: 22°C', 'London: 14°C']
注意事项
map方法会跳过空位但不会跳过undefined或null值。回调函数必须包含return语句,否则新数组将充满undefined。
const arr = [1, 2, , 4];
const mapped = arr.map(x => x * 2);
// [2, 4, empty, 8]
性能考虑
对于大型数组,map可能不是最高效的选择,因为它会创建新数组。如果不需要新数组,forEach可能是更好的选择。现代JavaScript引擎已对map进行了高度优化,在大多数情况下性能差异可以忽略。






