JavaScript Array map() 方法详解

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]

注意事项

  1. 不修改原数组map() 不会改变原数组
  2. 返回新数组:总是返回一个新数组
  3. 跳过空位:对于稀疏数组,空位会被跳过
  4. 性能考虑:对于大型数组,考虑性能影响
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 开发中不可或缺的工具。

相关推荐
Syron1 分钟前
为什么微应用不需要配置 try_files?
前端
前端老宋Running2 分钟前
别再写 API 路由了:Server Actions 才是全栈 React 的终极形态
前端·react.js·架构
王小酱2 分钟前
Cursor 的 Debug模式的核心理念和使用流程
前端·cursor
前端老宋Running3 分钟前
跟“白屏”说拜拜:用 Next.js 把 React 搬到服务器上,Google 爬虫都要喊一声“真香”
前端·react.js·架构
玉宇夕落3 分钟前
深入理解 React 与 JSX:从组件到 UI 构建
前端·react.js
jun_不见4 分钟前
面试官:你能说下订阅发布模式么,怎么在VUE项目中实现一个类似eventBus的事件总线呢
前端·javascript·面试
How_doyou_do4 分钟前
前端动画的多种实现方式
前端
南山安5 分钟前
React学习:组件化思想
javascript·react.js·前端框架
xhxxx5 分钟前
别再被 CSS 定位搞晕了!5 种 position 一图打尽 + 实战代码全公开
前端·css·html
OpenTiny社区5 分钟前
从千问灵光 App 看生成式 UI 技术的发展
前端·vue.js·ai编程