实现说明
flat1、flat2、flatAll 定义在模块顶层,中间不经过函数作用域。
常见问题
不安装任何包也能运行吗?
可以,开箱即跑——没有引用任何内建 API 之外的东西。 文件用顶层绑定保存自己的状态:flat1、flat2、flatAll。
核心语句
const flatAll = nested.flat(Infinity);
const flat1 = nested.flat(1);
const flat2 = nested.flat(2);
代码示例
const nested: Array<number | Array<number | Array<number>>> = [
1,
[2, 3],
[4, [5]],
];
const flat1 = nested.flat(1);
const flat2 = nested.flat(2);
const flatAll = nested.flat(Infinity);
// 类型跟着深度走:flat(1) 还保留一层嵌套,flat(2) 与 Infinity 才是纯 number
type One = typeof flat1;
type Two = typeof flat2;
const pure: number[] = flat2;
console.log(JSON.stringify(flat1), JSON.stringify(flat2), JSON.stringify(flatAll));
console.log(flat1.length, flat2.length, flatAll.length, pure.length);