JavaScript中的扁平化输出

26 次浏览 1 分钟阅读 0 个喜欢
arr = [1, [2, [3, [4, 5, [6, [7, [8, [9]]]]]]]]

console.log(arr.flat(10)) // 递归的层数 ,如果指定底层数大于数组实际层数将按照数组最高层数执行

arr = [1,2,3];

console.log(arr.map(x => [x*2])) // 输出的是 [Array(1), Array(1)....]

有没有办法直接输出 2,4,6呢?
之前我们讲过flat,这时候可以在map之后加上flat即可

console.log(arr.map(x => [x*2]).flat()) //输出的是 [2,4,6]

flat还提供一个API
就不需要我们写的这么多了

console.log(arr.flatMap(x => [x*2])) // 同样输出 [2,4,6]