js map实现
map 方法的基本用法
map 是 JavaScript 数组的一个高阶函数,用于遍历数组并对每个元素执行指定的操作,最终返回一个新数组。原数组不会被修改。
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
map 方法的参数
map 方法接受一个回调函数作为参数,回调函数可以接收三个参数:
currentValue:当前处理的数组元素。index(可选):当前元素的索引。array(可选):调用map的数组本身。
const numbers = [1, 2, 3];
const squaredWithIndex = numbers.map((num, index) => `${index}: ${num * num}`);
console.log(squaredWithIndex); // ["0: 1", "1: 4", "2: 9"]
使用 thisArg 绑定上下文
map 方法的第二个参数是 thisArg,用于指定回调函数中的 this 值。
const obj = {
multiplier: 2,
multiply(numbers) {
return numbers.map(function(num) {
return num * this.multiplier;
}, this);
}
};
console.log(obj.multiply([1, 2, 3])); // [2, 4, 6]
手动实现 map 方法
以下是一个手动实现 map 方法的示例:

Array.prototype.myMap = function(callback, thisArg) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback.call(thisArg, this[i], i, this));
}
return result;
};
const numbers = [1, 2, 3];
const tripled = numbers.myMap(num => num * 3);
console.log(tripled); // [3, 6, 9]
map 方法的常见用途
- 转换数组元素:将数组中的每个元素转换为另一种形式。
- 提取对象属性:从对象数组中提取特定属性。
- 生成新数据结构:将数组转换为另一种数据结构(如对象或字符串)。
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const names = users.map(user => user.name);
console.log(names); // ["Alice", "Bob", "Charlie"]
注意事项
map方法不会改变原数组,而是返回一个新数组。- 回调函数必须显式返回值,否则新数组会填充
undefined。 - 稀疏数组(包含空位)的
map行为会跳过空位。






