实现说明
各个操作都建立在顶层绑定之上: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));