• 【基础恶补】JavaScript数组的一些方法,reduce,filter,reverse,map等


    reduce

    reduce方法会对数组中的每个元素按序执行由你提供的reducer函数,每一次运行reducer会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。

    用法,两个参数callbackFn 和 initialValue

    reduce(callbackFn, initialValue)
    // 箭头函数
    
    reduce((pre,cur,curIndex,array) =>{
    ...
    }, initialValue)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    callbackFn即上文提到的reducer函数,里面包含四个参数:

    • previousValue:上一次调用 callbackFn 时的返回值。在第一次调用时,若指定了初始值 initialValue,其值则为 initialValue,否则为数组索引为 0 的元素 array[0]。
      -currentValue:数组中正在处理的元素。在第一次调用时,若指定了初始值 initialValue,其值则为数组索引为 0 的元素 array[0],否则为 array[1]。
    • currentIndex:数组中正在处理的元素的索引。若指定了初始值
    • initialValue,则起始索引号为 0,否则从索引 1 起始。
    • array:用于遍历的数组。

    initialValue: 这个参数是一个可选参数,作为第一次调用reducer时的previousValue.
    若指定了初始值 initialValue,则 currentValue 则将使用数组第一个元素;否则 previousValue 将使用数组第一个元素,而 currentValue 将使用数组第二个元素。

    返回值:使用“reducer”回调函数遍历整个数组后的结果

    示例

    1、累加求和

    let total = [ 0, 1, 2, 3 ].reduce(
      ( previousValue, currentValue ) => previousValue + currentValue,
      0
    )
    
    • 1
    • 2
    • 3
    • 4

    2、累加对象中的值

    const arr = [{ x: 1 }, { x: 3 }, { x: 5 }];
    const countValue = arr.reduce((pre, cur) => {
         return pre + cur?.x;
     }, 0);
    
    • 1
    • 2
    • 3
    • 4

    3、将二维数组转换为一维数组

     const arr = [[0, 1], [2, 3], [4, 5]];
     const flattened = arr.reduce((pre, cur) => {
         return pre.concat(cur
     }, []);
    
    • 1
    • 2
    • 3
    • 4

    4、计算数组中每个元素出现的次数

      let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice','Bob']
      let countNames = names.reduce((pre,cur) => {
          if(cur in pre){
              pre[cur]++
          }else{
              pre[cur] = 1
          }
          return pre;
      }, {} as any)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    5、按属性对object分类

      let people = [
          { name: 'Alice', age: 21 },
          { name: 'Max', age: 20 },
          { name: 'Jane', age: 20 }
        ];
      let groupBy = people.reduce((pre,cur) => {
          if(cur?.age in pre){
              pre[cur?.age].push(cur)
          }else{
              pre[cur?.age] = [cur]
          }
          return pre;
      }, {} as any)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    6、使用扩展运算符和 initialValue 绑定包含在对象数组中的数组

     let friends = [{
         name: 'Anna',
         books: ['Bible', 'Harry Potter'],
         age: 21
         }, {
         name: 'Bob',
         books: ['War and peace', 'Romeo and Juliet'],
         age: 26
         }, {
         name: 'Alice',
         books: ['The Lord of the Rings', 'The Shining'],
         age: 18
     }];
     const books = friends.reduce((pre, cur) => {
         return [...pre,...cur.books]
     }, ['Abookss']);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    7、使用 .reduce() 替换 .filter().map()
    reduce 只会遍历一次,
    而filter和map会遍历两次,reduce更加高效

    filter

    filter方法创建给定数组一部分的浅拷贝,其包含通过所提供函数实现的测试的所有元素。

    返回值:一个新的、通过测试的元素组成的数组,如果没有符合条件的,则返回一个空数组。

    参数 两个参数:callbackFn、thisArg

    filter(callbackFn,thisArg)
    
    • 1

    callbackFn:

    • element
      数组中当前正在处理的元素。
    • index
      正在处理的元素在数组中的索引。
    • array
      调用了 filter() 的数组本身。

    thisArg: 执行callback时,用于this的值。

    示例
    1、过滤json中的无效条目

            const arr = [
                { id: 15 },
                { id: -1 },
                { id: 0 },
                { id: 3 },
                { id: 12.2 },
                {},
                { id: null },
                { id: NaN },
                { id: 'undefined' },
            ];
            const newArr = arr.filter((item) => {
                if (item?.id !== 0 && Number.isFinite(item?.id)) return true;
                return false;
            });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    Number.isFinite() 用来检测传入的参数是否是一个有穷数。返回布尔值。
    那么…… 什么是有穷值?
    我没有找到合适的解释,不过可以看看下面的例子,有知道的阔以告诉我~~

    Number.isFinite(Infinity);  // false
    Number.isFinite(NaN);       // false
    Number.isFinite(-Infinity); // false
    
    Number.isFinite(0);         // true
    Number.isFinite(2e64);      // true
    
    Number.isFinite('0');       // false, would've been true with
                                // global isFinite('0');
                                
    Number.isFinite(null);      // false, would've been true with
                                // global isFinite(null)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    forEach

    map

    map 方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。

    ["1", "2", "3"].map(parseInt);
    
    • 1

    期望输出 [1, 2, 3], 而实际结果是 [1, NaN, NaN].
    因为parseInt 在这里接受了两个参数,一个是遍历的元素item,一个是下标值
    修改后:

    ["1", "2", "3"].map(parseInt(item,10));
    
    • 1

    其他方法:
    .at() 接收一个整数值并返回该索引对应的元素,允许正数和负数。负整数从数组中的最后一个元素开始。
    contact 用于合并两个或者多个数组。不会改变原有数组,而是返回一个新数组。
    entries 返回一个新的数组迭代器对象,该对象包含数组中每个索引的键、值对。
    every 测试一个数组内所有的元素是否都能通过某个指定函数的测试。返回一个布尔值。
    判断数组里的元素是否都大于10

            const arr = [12, 5, 8, 130, 44];
            const isTen = arr.every((item: number) => item > 10);
    
    • 1
    • 2

    fill: 用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。
    语法:

    fill(value)
    fill(value, start)
    fill(value, start, end)
    
    • 1
    • 2
    • 3

    find 返回数组中满足提供的测试函数的第一个元素的值。否则返回undefined

    find((element, index, array) => { /* … */ } )
    
    • 1

    findIndex() 和find类似,返回的是索引
    findLast() 和find类似,返回的是满足条件的最后一个元素
    findLastIndex() 和findLast()类似,返回的是索引
    flat 会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并成一个新数组返回。

    flat()
    flat(depth)
    
    • 1
    • 2

    Array.from()
    对一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。
    includes 判断一个数组是否包含一个指定的值,如果包含返回true,否则false.
    indexOf 返回找到给定元素的第一个索引,不存在则返回-1
    isArray 确定传递的值是否是一个Array, 返回布尔值
    join 将一个数组的所有元素连接成一个字符串并返回。

    [12, 5, 8, 130, 44].join(); //12,5,8,130,44
    [12, 5, 8, 130, 44].join(""); //125813044
    [12, 5, 8, 130, 44].join("-"); //12-5-8-130-44
    
    • 1
    • 2
    • 3

    lastIndexOf 返回指定元素在数组中的最后一个索引,没有返回-1
    of() 通过可变数量的参数创建一个新的array示例。
    pop() 从数组删除最后一个元素,并返回这个元素,会更改原数 组
    push() 将一个或多个元素添加到数组的末尾,并返回该数组的新长度。会改变原数组。
    reverse() 将数组中元素的位置颠倒,并返回该数组。会改变原数组。
    shift() 从数组周狗删除第一个元素,并返回该值。改变原数组
    slice() 方法返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。

    slice(start, end)
    
    • 1

    其他用法:
    方法可以用来将一个类数组(Array-like)对象/集合转换成一个新数组。

     Array.prototype.slice.call(arguments);
     或者
     [].slice.call(arguments)
    
    • 1
    • 2
    • 3

    some() 测试数组中是不是至少有一个元素通过了被提供的函数测试。

    [12, 5, 8, 130, 44].some(ele => ele > 40) //true
    
    • 1

    sort() 对数组的元素进行排序,并返回数组。
    默认排序顺序是在将元素转换为字符串,然后比较它们的 UTF-16 代码单元值序列时构建的
    语法之一:

    // 箭头函数
    sort((a, b) => { /* … */ } )
    
    • 1
    • 2

    compareFn(a, b) 返回值 排序顺序
    0 a 在 b 后
    < 0 a 在 b 前
    === 0 保持 a 和 b 的顺序

    splice(): 通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。

    splice(start)
    splice(start, deleteCount)
    splice(start, deleteCount, item1)
    splice(start, deleteCount, item1, item2, itemN)
    
    • 1
    • 2
    • 3
    • 4

    toLocalString(): 返回一个字符串表示数组中的元素。数组中的元素将使用各自的 toLocaleString 方法转成字符串,这些字符串将使用一个特定语言环境的字符串(例如一个逗号 “,”)隔开。
    toString(): toString() 方法返回一个字符串,表示指定的数组及其元素。
    unshift() 将一个或多个元素添加到数组开头,会返回长度,会改变原数组。
    values() 方法返回一个新的 Array Iterator 对象,该对象包含数组每个索引的值。

  • 相关阅读:
    C++语法基础:函数指针
    html笔记__html常用标签
    马瑞利汽车企业ERP管理系统 毕业设计源码96118
    Maven部署打包多环境(开发、测试、生产)配置教程
    推文项目进展如何
    洛谷P2574 XOR的艺术
    Spring框架学习(二)---- 我的第一个Spring程序
    【Linux】【网络】UDP、TCP 网络接口及使用
    微信小程序手写时间间隔组件,可设置间隔时间一分钟,半小时,一小时的间隔
    C++模板编程(24)---模板自变量推导Template Argument Deduction
  • 原文地址:https://blog.csdn.net/TanMengyi/article/details/128132435