js map方法 实现
map方法的基本概念
map是JavaScript数组的一个高阶函数,用于遍历数组并对每个元素执行指定操作,最终返回一个新数组。原数组不会被修改。
基本语法
const newArray = array.map(function(currentValue, index, arr) {
// 返回处理后的元素
}, thisArg);
currentValue: 当前处理的元素index(可选): 当前元素的索引arr(可选): 正在遍历的数组thisArg(可选): 执行回调时的this值
简单示例
将数字数组中的每个元素乘以2:
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
// doubled: [2, 4, 6]
处理对象数组
提取对象数组中的特定属性:
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
const names = users.map(user => user.name);
// names: ['Alice', 'Bob']
使用索引参数
为每个元素添加其索引值:
const letters = ['a', 'b', 'c'];
const indexed = letters.map((letter, index) => `${letter}${index}`);
// indexed: ['a0', 'b1', 'c2']
箭头函数简写
当只需要简单返回表达式时,可用箭头函数简写:
const nums = [1, 2, 3];
const squares = nums.map(x => x * x);
// squares: [1, 4, 9]
注意事项
map总会返回一个新数组,即使回调函数简单返回元素本身。如果需要过滤元素,应使用filter方法。

性能考虑
对于大型数组,map可能不如传统的for循环高效,但在大多数日常场景中,其可读性和功能性优势更值得考虑。






