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 开发中不可或缺的工具。

相关推荐
WeiXiao_Hyy4 分钟前
成为 Top 1% 的工程师
java·开发语言·javascript·经验分享·后端
吃杠碰小鸡21 分钟前
高中数学-数列-导数证明
前端·数学·算法
kingwebo'sZone27 分钟前
C#使用Aspose.Words把 word转成图片
前端·c#·word
xjt_09011 小时前
基于 Vue 3 构建企业级 Web Components 组件库
前端·javascript·vue.js
我是伪码农1 小时前
Vue 2.3
前端·javascript·vue.js
夜郎king1 小时前
HTML5 SVG 实现日出日落动画与实时天气可视化
前端·html5·svg 日出日落
辰风沐阳2 小时前
JavaScript 的宏任务和微任务
javascript
夏幻灵2 小时前
HTML5里最常用的十大标签
前端·html·html5
冰暮流星2 小时前
javascript之二重循环练习
开发语言·javascript·数据库
Mr Xu_3 小时前
Vue 3 中 watch 的使用详解:监听响应式数据变化的利器
前端·javascript·vue.js