在JavaScript中,map方法使用指南
JavaScript中map方法使用指南
map()
是JavaScript数组最常用的方法之一,它允许你遍历数组中的每个元素并返回一个新数组,而不会改变原数组。
基本用法
const newArray = array.map(callback(currentValue, index, array))
参数说明:
callback
- 对每个元素执行的函数currentValue
- 当前处理的元素index
(可选) - 当前元素的索引array
(可选) - 调用map的数组
示例演示
// 基础示例:将数字数组中的每个元素加倍
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]// 从对象数组中提取特定属性
const users = [{ id: 1, name: '张三', age: 25 },{ id: 2, name: '李四', age: 30 },{ id: 3, name: '王五', age: 28 }
];const names = users.map(user => user.name);
console.log(names); // ['张三', '李四', '王五']// 格式化数据
const formattedUsers = users.map(user => ({姓名: user.name,年龄: user.age + '岁'
}));
console.log(formattedUsers);
// [{姓名: '张三', 年龄: '25岁'}, ...]
实用技巧
// 1. 处理DOM元素
const elements = document.querySelectorAll('.item');
const texts = Array.from(elements).map(el => el.textContent);// 2. 结合解构使用
const points = [{x: 1, y: 2}, {x: 3, y: 4}];
const xCoords = points.map(({x}) => x);// 3. 使用索引参数
const items = ['a', 'b', 'c'];
const indexedItems = items.map((item, index) => `${index + 1}. ${item}`);
// ['1. a', '2. b', '3. c']// 4. 链式调用
const result = [1, 2, 3, 4, 5].filter(num => num % 2 === 0) // [2, 4].map(num => num * 3) // [6, 12].map(num => `数值: ${num}`);
// ['数值: 6', '数值: 12']
注意事项
// 1. map不会改变原数组
const original = [1, 2, 3];
const mapped = original.map(x => x * 2);
console.log(original); // [1, 2, 3] (未改变)
console.log(mapped); // [2, 4, 6]// 2. 处理稀疏数组
const sparseArray = [1, , 3];
const result = sparseArray.map(x => x * 2);
console.log(result); // [2, empty, 6]// 3. 使用thisArg参数(不常用)
const multiplier = {factor: 10,multiply: function(numbers) {return numbers.map(function(num) {return num * this.factor;}, this); // 第二个参数指定this}
};
console.log(multiplier.multiply([1, 2, 3])); // [10, 20, 30]
实际应用场景
// 价格格式化
const prices = [19.99, 29.99, 39.99];
const formattedPrices = prices.map(price => `¥${price.toFixed(2)}`
);// API数据处理
const apiResponse = [{ id: 1, title: '文章1', content: '内容1' },{ id: 2, title: '文章2', content: '内容2' }
];const simplifiedData = apiResponse.map(item => ({id: item.id,title: item.title
}));// 数据转换
const data = ['2023-01-01', '2023-02-15', '2023-03-20'];
const dateObjects = data.map(dateStr => new Date(dateStr));
与其他方法的比较
forEach()
- 只遍历,不返回值filter()
- 返回符合条件的元素reduce()
- 将数组缩减为单个值map()
- 返回处理后的新数组
map()
是函数式编程的重要工具,它使代码更简洁、可读性更强,并且避免了副作用。