Array.map() 简明指南 🎯

🔍 基本作用

创建 一个 新数组,其中 每个元素 都是 原数组的每个元素 调用函数 后的结果

// 语法
const newArray = array.map(callback(currentValue, index, array))

🚀 基本用法

1. 简单转换

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);

console.log(doubled); // [2, 4, 6, 8]

2. 对象数组转换

const users = [
    { name: '张三', age: 25 },
    { name: '李四', age: 30 }
];

const names = users.map(user => user.name);
console.log(names); // ['张三', '李四']

📝 参数详解

array.map((当前元素, 索引, 原数组) => {
    return 新元素;
})

完整参数使用

const numbers = [10, 20, 30];

const result = numbers.map((num, index, arr) => {
    return {
        value: num,
        position: index,
        total: arr.length
    };
});

console.log(result);
// [
//   { value: 10, position: 0, total: 3 },
//   { value: 20, position: 1, total: 3 },
//   { value: 30, position: 2, total: 3 }
// ]

🎯 实际应用场景

1. 数据格式化

const dates = ['2023-01-01', '2023-02-15'];
const formatted = dates.map(date => {
    const [year, month, day] = date.split('-');
    return `${year}${month}${day}日`;
});

console.log(formatted); // ['2023年01月01日', '2023年02月15日']

2. DOM 操作

// 获取所有按钮的文本内容
const buttons = document.querySelectorAll('button');
const buttonTexts = Array.from(buttons).map(btn => btn.textContent);

3. API 数据处理

const apiResponse = [
    { id: 1, title: '文章1', content: '内容1' },
    { id: 2, title: '文章2', content: '内容2' }
];

const simplified = apiResponse.map(item => ({
    id: item.id,
    title: item.title
}));

console.log(simplified);
// [{id: 1, title: '文章1'}, {id: 2, title: '文章2'}]

与 for 循环对比

传统 for 循环

const numbers = [1, 2, 3];
const doubled = [];

for (let i = 0; i < numbers.length; i++) {
    doubled.push(numbers[i] * 2);
}

map() 方法(更简洁)

const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);

🎯 重要特性

1. 不修改原数组

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 numbers = [1, 2, 3, 4, 5];

const result = numbers
    .filter(num => num > 2)        // [3, 4, 5]
    .map(num => num * 3)           // [9, 12, 15]
    .map(num => num.toString());   // ['9', '12', '15']

console.log(result);

💡 实用技巧

处理稀疏数组

const sparse = [1, , 3]; // 中间有空位
const result = sparse.map(x => x * 2);

console.log(result); // [2, empty, 6]

与 parseInt 的坑

// ❌ 错误用法
['1', '2', '3'].map(parseInt); // [1, NaN, NaN]

// ✅ 正确用法
['1', '2', '3'].map(num => parseInt(num)); // [1, 2, 3]

🎯 一句话总结

Array.map() 是数组的”转换器”,把 原数组的每个元素 按照 指定规则转换,生成一个 全新的数组!