JavaScript Array map() 方法详解
map() 是 JavaScript 数组方法中非常强大且常用的方法之一,它允许我们遍历数组并对每个元素执行指定的操作,然后返回一个新数组。
基本语法
javascript
const newArray = array.map(callback(currentValue[, index[, array]])[, thisArg])
参数说明:
callback:对每个数组元素执行的函数currentValue:当前正在处理的元素index(可选):当前元素的索引array(可选):调用 map 的数组本身
thisArg(可选):执行 callback 时使用的 this 值
基本用法示例
javascript
// 示例1:将数字数组中的每个元素乘以2
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// 示例2:将字符串数组转换为大写
const fruits = ['apple', 'banana', 'orange'];
const upperCaseFruits = fruits.map(fruit => fruit.toUpperCase());
console.log(upperCaseFruits); // ['APPLE', 'BANANA', 'ORANGE']
实际应用场景
1. 处理对象数组
javascript
const users = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 }
];
// 提取用户名数组
const userNames = users.map(user => user.name);
console.log(userNames); // ['Alice', 'Bob', 'Charlie']
// 创建新的对象数组
const userProfiles = users.map(user => ({
userId: user.id,
fullName: user.name,
isAdult: user.age >= 18
}));
console.log(userProfiles);
// [
// { userId: 1, fullName: 'Alice', isAdult: true },
// { userId: 2, fullName: 'Bob', isAdult: true },
// { userId: 3, fullName: 'Charlie', isAdult: true }
// ]
2. 处理 DOM 元素
javascript
// 假设有以下 HTML 结构
// <div class="item" data-price="10">Product A</div>
// <div class="item" data-price="15">Product B</div>
// <div class="item" data-price="20">Product C</div>
const items = document.querySelectorAll('.item');
const prices = Array.from(items).map(item => ({
name: item.textContent,
price: parseFloat(item.dataset.price)
}));
console.log(prices);
// [
// { name: 'Product A', price: 10 },
// { name: 'Product B', price: 15 },
// { name: 'Product C', price: 20 }
// ]
3. 数据转换和格式化
javascript
const dates = ['2023-01-15', '2023-02-20', '2023-03-25'];
const formattedDates = dates.map(date => {
const [year, month, day] = date.split('-');
return `${day}/${month}/${year}`;
});
console.log(formattedDates); // ['15/01/2023', '20/02/2023', '25/03/2023']
// 处理数字格式化
const prices = [19.99, 29.5, 45.75];
const formattedPrices = prices.map(price => `$${price.toFixed(2)}`);
console.log(formattedPrices); // ['$19.99', '$29.50', '$45.75']
使用索引参数
javascript
const items = ['a', 'b', 'c', 'd'];
const indexedItems = items.map((item, index) => `${index + 1}. ${item}`);
console.log(indexedItems); // ['1. a', '2. b', '3. c', '4. d']
使用 thisArg 参数
javascript
const multiplier = {
factor: 3,
multiply: function(number) {
return number * this.factor;
}
};
const numbers = [1, 2, 3, 4];
const tripled = numbers.map(function(num) {
return this.multiply(num);
}, multiplier);
console.log(tripled); // [3, 6, 9, 12]
链式调用
javascript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = numbers
.filter(num => num % 2 === 0) // 筛选偶数
.map(num => num * 2) // 乘以2
.map(num => num + 10); // 加10
console.log(result); // [14, 18, 22, 26, 30]
注意事项
- 不修改原数组 :
map()不会改变原数组 - 返回新数组:总是返回一个新数组
- 跳过空位:对于稀疏数组,空位会被跳过
- 性能考虑:对于大型数组,考虑性能影响
javascript
// 原数组不会被修改
const original = [1, 2, 3];
const mapped = original.map(x => x * 2);
console.log(original); // [1, 2, 3] (不变)
console.log(mapped); // [2, 4, 6] (新数组)
// 处理稀疏数组
const sparseArray = [1, , 3];
const result = sparseArray.map(x => x * 2);
console.log(result); // [2, empty, 6]
与 forEach 的区别
javascript
const numbers = [1, 2, 3];
// map() 返回新数组
const mapped = numbers.map(num => num * 2);
console.log(mapped); // [2, 4, 6]
// forEach() 不返回值(返回 undefined)
const forEachResult = numbers.forEach(num => num * 2);
console.log(forEachResult); // undefined
实际项目示例
javascript
// API 数据处理
const apiResponse = [
{ id: 1, title: 'Post 1', body: 'Content 1', userId: 1 },
{ id: 2, title: 'Post 2', body: 'Content 2', userId: 2 },
{ id: 3, title: 'Post 3', body: 'Content 3', userId: 1 }
];
// 转换为前端需要的格式
const formattedPosts = apiResponse.map(post => ({
postId: post.id,
title: post.title.toUpperCase(),
content: post.body,
authorId: post.userId,
createdAt: new Date().toISOString()
}));
console.log(formattedPosts);
map() 方法是函数式编程风格的重要组成部分,它使代码更加简洁、可读,并且避免了副作用,是现代 JavaScript 开发中不可或缺的工具。