map() 高阶函数
map()
高阶函数用法
定义
map()
方法是数组原型的一个函数,该函数用于对数组中的每个元素进行处理,将其转换为另一个值,最终返回一个新的数组,该数组包含了经过处理后的每个元素。
基本语法:
array.map(callback(currentValue[, index[, array]])[, thisArg])
callback
:表示对数组中的每个元素要执行的函数。该函数包含三个参数:currentValue
:表示正在处理的当前元素。index
:可选参数,表示正在处理的当前元素的索引。array
:可选参数,表示正在处理的当前数组。
thisArg
:可选参数,表示执行callback
函数时的this
值。
基本用法
使用
map()
方法将数组中的数字乘以 2 并返回新的数组:1
2
3
4
5
6let numbers = [1, 2, 3, 4];
let doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // 输出 [2, 4, 6, 8]
console.log(numbers); // 输出 [1, 2, 3, 4],原数组并没有发生变化字符串处理:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15// 将字符串数组转换为数字数组:
let strings = ['1', '2', '3'];
let numbers = strings.map(function(str) {
return parseInt(str, 10); //第二个参数表示转化为十进制
});
console.log(numbers); // 输出 [1, 2, 3]
// 将一个数组中的字符串转换为另一个数组,只保留长度大于等于5的字符串:
const words = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
const longWords = words.map(function(word) {
if (word.length >= 5) {
return word;
}
});
console.log(longWords); // ['apple', 'banana', 'cherry', undefined, 'elderberry']对象数组处理:
1
2
3
4
5let objects = [{ name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'orange', color: 'orange' }];
let colors = objects.map(function(obj) {
return obj.color;
});
console.log(colors); // 输出 ["red", "yellow", "orange"]可以选择传递可选参数
thisArg
来设置回调函数的this
值。如果不传递thisArg
参数,则默认情况下,回调函数的this
值为undefined
。1
2
3
4
5
6let numbers = [1, 2, 3];
let obj = { multiplier: 2 };
let doubled = numbers.map(function(num) {
return num * this.multiplier;
}, obj);
console.log(doubled); // 输出 [2, 4, 6]- 上面的例子中,我们定义了一个名为
numbers
的数组,其中包含三个数字。我们还定义了一个名为obj
的对象,其中包含一个名为multiplier
的属性,该属性的值为 2。我们在回调函数中使用this.multiplier
,其中this
值为obj
,来将数组中的每个元素乘以 2。
- 上面的例子中,我们定义了一个名为
优缺点
优点:
map()
默认会有返回值,一般返回一个数组。所以这个也是map()
的一个特色- 这里要强调一下,函数默认没有返回值。如果函数内部没有明确使用 return 语句返回一个值,那么该函数执行完毕后会自动返回
undefined
。
- 这里要强调一下,函数默认没有返回值。如果函数内部没有明确使用 return 语句返回一个值,那么该函数执行完毕后会自动返回
- 可以方便地对数组中的每个元素进行操作,并生成一个新的数组;
- 不会改变原始数组。
缺点:
- 无法使用
break
,continue
,return
等关键字控制循环,必须全部遍历完毕才能停止; - 对于大型数据集合而言,可能会导致性能问题。
数据小的时候,用 map()
循环非常的爽,不是很消耗性能。但数据大的情况下,用 map()
会很耗性能,因为 map()
会对数组中的每个元素执行一次callback
方法。建议数据大的时候,用for循环。虽然多次for循环嵌套看着恶心,但是性能好,是底层的东西。而所谓的map()
,set()
,for in
,for of
都是在for循环的基础上再封装。单从性能角度考虑,远不如 for 循环优秀。
其他用法
map循环配合
Array.from()
去重1
2
3const arr = [1, 2, 2, 3, 4, 4, 5];
const newArr = Array.from(new Map(arr.map(item => [item, item])).values());
console.log(newArr); // [1, 2, 3, 4, 5]- 先使用
map
方法将数组元素映射为键值对的数组。 - 使用
Map
构造函数将键值对数组转换为Map
对象,其中键和值均为数组的元素。由于Map
对象中键是唯一的,这样就自动去除了数组中的重复项。- 最后,通过Array.from()
方法将去重后的Map
对象的值转换为新的数组。
- 先使用
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Fred's Blog!