Array.prototype.map()
是 JavaScript 中的一个数组方法,它创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后的返回值。
map()
方法接收一个回调函数作为参数,这个回调函数会被数组的每个元素依次调用。回调函数接收三个参数:
currentValue
(当前元素)index
(当前元素的索引)array
(调用 map
的数组)map()
可以用一行代码完成对数组元素的转换,使代码更加简洁易读。map()
不会改变原始数组,而是返回一个新数组,这有助于避免副作用。map()
是函数式编程风格的一部分,它鼓励使用纯函数来处理数据。map()
方法本身没有类型,但回调函数可以根据需要返回任何类型的值,因此 map()
可以产生任何类型的数组。
map()
本身是同步的,但可以与 Promise.all()
结合使用来并行处理异步操作。// 将数组中的每个数字乘以 2
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // 输出: [2, 4, 6, 8]
// 使用箭头函数简化代码
const doubledWithArrow = numbers.map(num => num * 2);
console.log(doubledWithArrow); // 输出: [2, 4, 6, 8]
// 将字符串数组转换为大写
const strings = ['apple', 'banana', 'cherry'];
const uppercased = strings.map(str => str.toUpperCase());
console.log(uppercased); // 输出: ['APPLE', 'BANANA', 'CHERRY']
map()
方法没有改变原始数组?map()
方法设计为非变异方法,这意味着它不会修改调用它的原始数组。这是为了防止意外的副作用,确保函数的纯净性。如果你需要修改原始数组,可以使用 forEach()
方法或者在 map()
返回的新数组上进行操作后赋值回原数组。
如果你确实需要改变原始数组,可以使用 forEach()
:
const numbers = [1, 2, 3, 4];
numbers.forEach((num, index, arr) => {
arr[index] = num * 2;
});
console.log(numbers); // 输出: [2, 4, 6, 8]
或者使用 map()
后赋值回原数组:
let numbers = [1, 2, 3, 4];
numbers = numbers.map(num => num * 2);
console.log(numbers); // 输出: [2, 4, 6, 8]
这样既保持了代码的清晰性,又达到了修改原始数组的目的。
领取专属 10元无门槛券
手把手带您无忧上云