Array.prototype.flatMap()
flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。它与 map 连着深度值为1的 flat 几乎相同,但 flatMap 通常在合并成一种方法的效率稍微高一些。
由于我只用于扁平化,具体参数看文档。
代码如下:
1 2 3 4 5 | //只有一层 const arr1 = [1, 2, 3, 4,[5],6,[7]]; const res=arr1.flatMap(x =>x) console.log(res); //打印:(7) [1, 2, 3, 4, 5, 6, 7] |
1 2 3 4 5 | //两层时 const arr2 = [1, 2, 3, 4,[[5]],6,[[[7]]]]; const res=arr2.flatMap(x =>x) console.log(res); 打印:[1, 2, 3, 4, [5], 6, [7]] |
注意:flatMap()只能扁平化一层数组,所有当只有一层的时候用,效率更高。
Array.prototype.flat()
flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
参数:depth 可选–(指定要提取嵌套数组的结构深度,默认值为 1)
返回值:一个包含将数组与子数组中所有元素的新数组。
代码如下:
1 2 3 4 | //depth可选,默认1 const arr1 = [1, 2, 3, 4,[5],6,[7]]; console.log(arr1.flat()); //打印:(7) [1, 2, 3, 4, 5, 6, 7] |
1 2 3 4 | //depth---2 const arr1 = [1, 2, 3, 4,[[5]],[6],[[7]],[[8]]]; console.log(arr1.flat(2)); //打印:(7) [1, 2, 3, 4, 5, 6, 7] |
1 2 3 4 | //depth---Infinity 不管有多少层嵌套,都要转成一维数组 const arr1 = [1, 2, 3, 4,[[5]],[6],[[7]],[[8]],[[[[[[9]]]]]] ]; console.log(arr1.flat(Infinity)); //打印:(9) [1, 2, 3, 4, 5, 6, 7, 8, 9] |
1 2 3 | 注意:如果原数组有空位,flat()方法会跳过空位。 [1, 2, , 4, 5].flat() // [1, 2, 4, 5] |