map
是数组的高阶函数,它不会修改原始数组,而是返回一个新数组,其中包含了对原始数组每个元素执行操作后的结果。
基本语法
const newArray = array.map((element, index, array) => {
// 进行操作
return newElement;
});
示例
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // 输出: [2, 4, 6, 8]
使用索引
const numbers = [10, 20, 30];
const indexed = numbers.map((num, index) => `${index}: ${num}`);
console.log(indexed); // 输出: ["0: 10", "1: 20", "2: 30"]
处理对象数组
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const usernames = users.map(user => user.name);
console.log(usernames); // 输出: ["Alice", "Bob", "Charlie"]
与其他函数结合使用 如filter、map
const numbers = [1, 2, 3, 4, 5];
const result = numbers
.filter(num => num % 2 === 0) // 先筛选出偶数
.map(num => num * 10); // 然后将偶数乘以 10
console.log(result); // 输出: [20, 40]