其他分享
首页 > 其他分享> > 数组扁平的常见方法

数组扁平的常见方法

作者:互联网

1.toString + split,可以处理多维数组,但不能包含特殊的子元素如null,undefined,对象等   console.log(arr1.toString());   console.log(arr1.toString().split(","));   const newarr2 = arr1.toString().split(",").map(item=>{   return +item   })   console.log(newarr2);   2.concat+扩展运算符,缺点只能展开二维数组   console.log(...arr1);//把数组元素展开成独立的元素   console.log([].concat(...arr1));   3.reduce + concat, 只能展开二维数组   1.定义和用法   2.reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。   3.reduce() 可以作为一个高阶函数,用于函数的 compose。     注意: reduce() 对于空数组是不会执行回调函数的。   4.语法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)     参数:       total 必需。初始值, 或者计算结束后的返回值。       currentValue 必需。当前元素       currentIndex 可选。当前元素的索引       arr 可选。当前元素所属的数组对象。       initialValue 可选。传递给函数的初始值     eg:     const arr2 = [1,2,3,4,5];     const sum = arr2.reduce((pre,item,index,arr)=>{     console.log(pre,item,index,arr);     return pre + item;     },0)     console.log(sum);     const newarr1 = arr1.reduce((pre,item) => {   return pre.concat(item)   },[])   console.log(newarr1);   4.flat方法   1.概念:flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。   2.语法:arr.flat(depth),depth指定要提取嵌套数组的结构深度默认值为1,infinity可以展开任意深度的嵌套数组   3.返回值:一个包含将数组与子数组中所有元素的新数组。   const arr1 = [1,2,3,[1,2,3]];   console.log(arr1.flat());  

标签:console,log,常见,reduce,数组,item,扁平,arr1
来源: https://www.cnblogs.com/linen/p/15962761.html