map() 高阶函数用法

定义

map() 方法是数组原型的一个函数,该函数用于对数组中的每个元素进行处理,将其转换为另一个值,最终返回一个新的数组,该数组包含了经过处理后的每个元素。

  • 基本语法:array.map(callback(currentValue[, index[, array]])[, thisArg])

    • callback :表示对数组中的每个元素要执行的函数。该函数包含三个参数:

      • currentValue:表示正在处理的当前元素。

      • index:可选参数,表示正在处理的当前元素的索引。

      • array:可选参数,表示正在处理的当前数组。

    • thisArg:可选参数,表示执行 callback 函数时的 this 值。

基本用法

  • 使用 map() 方法将数组中的数字乘以 2 并返回新的数组:

    1
    2
    3
    4
    5
    6
    let 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
    5
    let 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
    6
    let 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
  • 可以方便地对数组中的每个元素进行操作,并生成一个新的数组;
  • 不会改变原始数组。

缺点:

  • 无法使用 breakcontinuereturn 等关键字控制循环,必须全部遍历完毕才能停止;
  • 对于大型数据集合而言,可能会导致性能问题。

数据小的时候,用 map() 循环非常的爽,不是很消耗性能。但数据大的情况下,用 map() 会很耗性能,因为 map() 会对数组中的每个元素执行一次callback方法。建议数据大的时候,用for循环。虽然多次for循环嵌套看着恶心,但是性能好,是底层的东西。而所谓的map()set()for infor of 都是在for循环的基础上再封装。单从性能角度考虑,远不如 for 循环优秀。

其他用法

  • map循环配合 Array.from() 去重

    1
    2
    3
    const 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 对象的值转换为新的数组。