es6 flat() flatMap()平铺数组
1.Array.prototype.flat()
用于将嵌套的数组“拉平”,变成一维数组。该方法返回一个新数组,对原数据没有影响
const a = [1,2,[5,3],['a','b']]
cosnt b = a.flat() // [1,2,5,3,'a','b']
2.可以传参数 平铺几维数组 如果不知道是多少层 可以传Infinity
const c = [1,2,['a','b','c'],[2,['e','r']]]
const d = c.flat() //[1, 2, "a", "b", "c", 2,['e','r']]
const e = c.flat(3) // [1, 2, "a", "b", "c", 2, "e", "r"]
const e = c.flat(Infinity) // [1, 2, "a", "b", "c", 2, "e", "r"]
3.如果原数组有空位,flat()方法会跳过空位,但是不过滤undefined
、null
、以及空字符串
const a = [1,2,[5,3],,['a','b'],undefined,null,1,'',4]
cosnt b = a.flat() // [1, 2, 5, 3, "a", "b", undefined, null, 1, "", 4]
4 flatMap()
方法对原数组的每个成员执行一个函数,相当于执行Array.prototype.map()
,然后对返回值组成的数组执行flat()
方法。该方法返回一个新数组,不改变原数组
[2, 3, 4].flatMap((x) => [x, x * 2])] // [2, 4, 3, 6, 4, 8] 先执行map 再执行 flat