把多维数组转化为一维数组
es6写法
const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v)); console.log(deepFlatten([1, [2], [[3], 4], 5,[6,[7,8],[[9,10],11,12],13,[14]]])); // [1,2,3,4,5,6,7,8,9,10,11,12,13,14] console.log(deepFlatten([[1,2,3],[2,4,6]])) // [1,2,3,4,5,6]
es10语法:flat(n)
// 用es10的flat 方法 console.log( [1, [2], [[3], 4], 5,[6,[7,8],[[9,10],11,12],13,[14]]].flat(4)); // [1,2,3,4,5,6,7,8,9,10,11,12,13,14] console.log( [[1,2,3],[2,4,6]].flat(4)); // [1,2,3,4,5,6]