前言
数组是 JS 中使用频率仅次于对象的数据结构,官方提供了众多的 API,谈谈如何扁平化(flatten)数组。...数组的扁平化,是将一个嵌套多层的数组 array (嵌套可以是任何层数)转换为只有一层的数组
flat
flat(depth) 方法会递归到指定深度将所有子数组连接,并返回一个新数组, depth指定嵌套数组中的结构深度...flat(2) // [1, 2, 3, 4]
[1, 2, [3, [4, [5]]]].flat(Infinity) // [1, 2, 3, 4, 5]
复制代码
flat()有兼容性问题, 不建议使用...arr) yield* flatten(el);
}
let flattened = [...flatten([1,[2,[3,[4]]]])]; // [1, 2, 3, 4]
复制代码
字符串过滤...(/\[|]/g,'')}]`);
复制代码
undercore or lodash 库
使用undercore库或者lodash的中_.flatten函数,具体用法查阅API文档
_.flatten(