map实现js
使用 map 方法遍历数组
map 是 JavaScript 数组的高阶函数,用于遍历数组并对每个元素执行回调函数,返回一个新数组。原数组不会被修改。
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
回调函数的参数
map 的回调函数接收三个参数:
- 当前元素
- 当前索引
- 原数组
const numbers = [1, 2, 3];
const mapped = numbers.map((num, index, arr) => {
return `${index}: ${num} (from array ${arr})`;
});
console.log(mapped);
// ["0: 1 (from array 1,2,3)", "1: 2 (from array 1,2,3)", "2: 3 (from array 1,2,3)"]
处理对象数组
map 可以用于转换对象数组中的属性:
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
const names = users.map(user => user.name);
console.log(names); // ["Alice", "Bob"]
链式调用
map 可以与其他数组方法链式调用:
const numbers = [1, 2, 3, 4];
const result = numbers
.filter(num => num % 2 === 0)
.map(num => num * 10);
console.log(result); // [20, 40]
注意事项
使用 map 时需注意:

- 必须显式使用
return语句返回新值(除非使用箭头函数简写) - 回调函数应是纯函数,避免副作用
- 稀疏数组中的空位会被跳过,但保留在结果数组中
const sparse = [1, , 3];
const mapped = sparse.map(x => x * 2);
console.log(mapped); // [2, empty, 6]






