map()
是 JavaScript 中数组对象的方法,用于创建一个新数组,数组中的每个元素都是通过调用提供的函数对原数组中的每个元素进行处理后的结果。它是一个高阶函数,广泛用于对数组元素进行批量转换或映射。
1. 基本语法
const newArray = array.map(function(currentValue, index, array) {
// Return a new value for the current element
});
currentValue
:当前处理的元素值。index
(可选):当前处理的元素索引。array
(可选):调用map()
的原数组。
2. 返回值
map()
方法返回一个新的数组,新数组中的每个元素是调用callback
函数的结果。map()
不会修改原始数组,但callback
中可以修改数组的内容。
3. 示例
3.1 基本用法
将一个数字数组中的每个元素都乘以 2:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(number) {
return number * 2;
});
console.log(doubled); // 输出: [2, 4, 6, 8, 10]
3.2 使用箭头函数
使用箭头函数来简化代码:
const doubled = numbers.map(number => number * 2);
console.log(doubled); // 输出: [2, 4, 6, 8, 10]
3.3 修改对象数组
假设有一个对象数组,你希望从每个对象中提取一个特定的属性:
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];
const names = users.map(user => user.name);
console.log(names); // 输出: ['Alice', 'Bob', 'Charlie']
3.4 使用索引
map()
的回调函数可以接收第二个参数,即数组元素的索引:
const numbers = [1, 2, 3, 4, 5];
const indexed = numbers.map((number, index) => `Index ${index}: ${number}`);
console.log(indexed);
// 输出:
// ['Index 0: 1', 'Index 1: 2', 'Index 2: 3', 'Index 3: 4', 'Index 4: 5']
4. map()
与其他方法的对比
forEach
:forEach
只是对数组每个元素执行函数,不返回新数组,而map()
会生成一个新数组。filter
:filter
返回的是通过测试的数组元素,而map()
只是对数组中的每个元素进行处理后生成一个新的数组。reduce
:reduce
可以用来做更复杂的数组处理,比如累加,而map()
仅用于将数组的每个元素映射到一个新的元素。
5. 常见误区
- 未返回新值:如果
map()
的回调函数没有显式返回一个值,生成的新数组将包含undefined。
const undefinedArray = [1, 2, 3].map(x => {
x * 2; // 没有返回值
});
console.log(undefinedArray); // 输出: [undefined, undefined, undefined]
正确的做法应该是显式返回新值:
const correctArray = [1, 2, 3].map(x => x * 2);
console.log(correctArray); // 输出: [2, 4, 6]
6. 链式调用
map()
可以与其他数组方法(如 filter()
和 reduce()
)链式调用来处理复杂的数组操作:
const numbers = [1, 2, 3, 4, 5, 6];
// 过滤出偶数并将其翻倍
const doubledEvens = numbers
.filter(n => n % 2 === 0)
.map(n => n * 2);
console.log(doubledEvens); // 输出: [4, 8, 12]
map()
是 JavaScript 中数组操作的一个重要工具,能够简洁、高效地转换数组内容。