map()
是 JavaScript 中一个非常常用的数组方法,它可以用来遍历一个数组并将每个元素映射到新的值上,最终返回一个新的数组。
map()
方法的基本语法如下:
array.map(callback(currentValue, index, array), thisArg)
其中,array
是要操作的数组,callback
是处理每个元素的回调函数。callback
函数接收三个参数:
currentValue
: 当前元素的值index
: 当前元素的索引array
: 原始数组
回调函数返回的值将成为映射后的新数组的元素。
以下是一个在数组中每个元素后添加 " is a fruit" 的例子:
const fruits = ['apple', 'banana', 'cherry'];
const fruitsWithMessage = fruits.map((fruit) => {
return fruit + ' is a fruit';
});
console.log(fruitsWithMessage); // ["apple is a fruit", "banana is a fruit", "cherry is a fruit"]
在这个例子中,map()
方法遍历了整个数组,对每个元素执行了回调函数,将每个元素和 " is a fruit" 相连后返回了一个新的数组。fruitsWithMessage
数组就是映射后的新数组。
map()
方法可以将一个数组转换为另一个数组,提取数组中的特定值或属性,或者进行任何其他类型的转换,具有很大的灵活性。
以下是 map()
方法的其他一些使用案例:
1.将数组中的每个元素转换为数字类型:
const arr = ['1', '2', '3'];
const numbers = arr.map((strNum) => {
return Number(strNum);
});
console.log(numbers); // [1, 2, 3]
2.提取数组中对象的某个属性:
const users = [
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 40},
];
const names = users.map((user) => {
return user.name;
});
console.log(names); // ['Alice', 'Bob', 'Charlie']
3.将二维数组里的每个元素相加
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
const sums = matrix.map((row) => {
return row.reduce((acc, curr) => acc + curr, 0);
});
console.log(sums); // [6, 15, 24]
在上面的例子中,我们先用 map()
方法遍历了二维数组的每行,并用 reduce()
方法对每行数组进行求和,最终返回了每行数组的总和。
总之,map()
方法是一个非常有用的数组方法,可以将一个数组映射到另一个数组上,提取特定的值或属性,或进行其他类型的转换。