reduce()方法
let arr = [[0, 1], [2, 3],[4, [5, 6, 7]]];
function dimensionReduction(val) {
return val.reduce((pre, cur) =>
pre.concat(Array.isArray(cur)) ? dimensionReduction(cur) : cur
);
}
dimensionReduction(arr)
flat()方法
//返回新数组
//flat()默认只会“拉平”一层,如果想要“拉平”多层的嵌套数组,可以将flat()方法的参数写成一个整数,表示想要拉平的层数,默认为1。
//如果不管有多少层嵌套,都要转成一维数组,可以用Infinity关键字作为参数。
//!!如果数组有空位flat()会跳过空位
[1, 2, [3, [4, 5]]].flat()
// [1, 2, 3, [4, 5]]
[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]
[1, 2, , 4, 5].flat()
// [1, 2, 4, 5]
flatMap()方法
//返回新数组
//flatMap()方法相当于es6 map数组循环方法吧每一项拿出使用flat()方法
//!!只能展开一层
[2, 3, 4].flatMap((item) => [item, item * 2])
// [2, 4, 3, 6, 4, 8]