JavaScript中Array.prototype.map的使用指南
在JavaScript数组操作中,Array.prototype.map是非常常用的高阶函数,它能够遍历数组的每个元素,对每个元素执行指定的处理函数,最终返回一个新的数组,且不会改变原数组。下面我们详细了解它的语法、参数和实际使用场景。
基本语法
map方法的语法结构如下:
const newArray = originalArray.map(callback(currentValue[, index[, array]])[, thisArg]);
其中各个参数的含义如下:
- callback:必选参数,用来处理每个数组元素的回调函数,该函数可以接收三个参数:
- currentValue:当前正在处理的数组元素
- index:可选,当前元素的索引值
- array:可选,调用map方法的原数组本身
- thisArg:可选参数,执行callback函数时使用的this指向
基础使用示例
最简单的场景是对数组中的每个元素进行统一运算,比如将数组中的所有数字乘以2:
// 原数组
const numbers = [1, 2, 3, 4, 5];
// 使用map处理每个元素,返回新数组
const doubledNumbers = numbers.map(function(num) {
return num * 2;
});
console.log(doubledNumbers); // 输出 [2, 4, 6, 8, 10]
console.log(numbers); // 原数组不变,输出 [1, 2, 3, 4, 5]如果使用箭头函数,代码会更简洁:
const numbers = [1, 2, 3, 4, 5]; const doubledNumbers = numbers.map(num => num * 2); console.log(doubledNumbers); // 输出 [2, 4, 6, 8, 10]
结合索引和原数组的使用
如果需要用到当前元素的索引或者原数组,也可以在回调函数中传入对应的参数,比如给数组每个元素加上它的索引值:
const arr = ['a', 'b', 'c', 'd'];
const newArr = arr.map((item, index) => {
return `${item}-${index}`;
});
console.log(newArr); // 输出 ['a-0', 'b-1', 'c-2', 'd-3']处理对象数组的场景
实际开发中经常会遇到对象数组,比如从接口获取的用户列表,需要提取其中的某个属性组成新数组,或者修改对象的部分属性,这时候map也非常实用:
// 用户对象数组
const users = [
{ id: 1, name: '张三', age: 20 },
{ id: 2, name: '李四', age: 22 },
{ id: 3, name: '王五', age: 25 }
];
// 提取所有用户的name组成新数组
const userNames = users.map(user => user.name);
console.log(userNames); // 输出 ['张三', '李四', '王五']
// 给每个用户对象新增一个isAdult属性,判断是否成年
const updatedUsers = users.map(user => {
return {
...user,
isAdult: user.age >= 18
};
});
console.log(updatedUsers);
// 输出 [
// { id: 1, name: '张三', age: 20, isAdult: true },
// { id: 2, name: '李四', age: 22, isAdult: true },
// { id: 3, name: '王五', age: 25, isAdult: true }
// ]注意事项
- map方法会返回一个新数组,数组的长度和原数组一致,即使回调函数没有返回任何值,新数组的对应位置也会是undefined。
- map方法不会改变原数组,如果需要修改原数组,可以考虑使用forEach方法,或者将map返回的新数组重新赋值给原变量。
- 空数组调用map方法会直接返回空数组,不会执行回调函数。
- 如果只需要遍历数组执行操作,不需要返回新数组,优先使用forEach方法,避免不必要的数组创建。
比如忘记写return的情况,新数组会出现undefined:
const arr = [1, 2, 3];
const result = arr.map(num => {
num * 2; // 没有return,返回undefined
});
console.log(result); // 输出 [undefined, undefined, undefined]
JavaScriptArray.prototype.map数组操作高阶函数前端开发 本作品最后修改时间:2026-05-23 23:13:43