← 中文资源

简体中文版本

flat 按深度展开嵌套数组

flat() 默认只展开一层,数字深度继续下钻,稀疏位会被顺手移除;flatMap 就是 map 之后接 flat(1)。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

flat()        : [ 1, 2, 3, 4, [ 5, 6 ] ]
flat(2)       : [ 1, 2, 3, 4, 5, 6 ]
flat(Infinity): [ 1, 2, 3, 4, 5, 6 ]
flatMap       : [ 'a', 'b', 'c', 'd' ]
holes         : [ 1, 3 ]
tree          : [ 1, 2, 3, 4, 5 ]

实现说明

各个操作都建立在顶层绑定之上:nested、words、withHoles、tree。

使用要点

  • 演示输出是带标签的(flat(Infinity):),每个操作都会留下自己的一行标注。

常见问题

有语言之外需要解析的导入吗?

没有。每个导入都解析到语言自带的模块。 跨调用保留的状态放在这些顶层绑定里:nested、words、withHoles。

核心语句

const nested = [1, [2, 3], [4, [5, 6]]];
const tree = [[1, [2]], [3, [4, [5]]]];
const words = ["ab", "cd"];

代码示例

const nested = [1, [2, 3], [4, [5, 6]]];

// flat(depth):默认只展开一层
console.log("flat()        :", nested.flat());
console.log("flat(2)       :", nested.flat(2));
console.log("flat(Infinity):", nested.flat(Infinity));

// flatMap = map 之后接 flat(1):一项拆多项时常用
const words = ["ab", "cd"];
console.log("flatMap       :", words.flatMap((word) => word.split("")));

// 稀疏位(empty slot)会被 flat 顺手移除
const withHoles = [1, , 3];
console.log("holes         :", withHoles.flat());

// 多层树形结构:flat(Infinity) 一次压平所有层
const tree = [[1, [2]], [3, [4, [5]]]];
console.log("tree          :", tree.flat(Infinity));