← 中文资源

简体中文版本

flatMap 只压平一层元素

flatMap 每次调用只压平一层:三层嵌套压完仍剩两层;分支要返回数组才能保持元素类型一致,返回空数组即可在映射的同时跳过元素。

阅读英文原文

运行结果

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

one level: [ 1, 2, 3, 4 ]
still nested: [[1,2],[3]]
labels: [ '1', '2', 'empty row', '3', '4' ]
kept: [ 'A', 'B' ]

使用要点

  • 演示输出是带标签的(one level:、still nested:、labels:),每个操作都会留下自己的一行标注。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。

核心语句

const once: number[][] = deep.flatMap((group) => group);
const numbers: number[] = rows.flatMap((row) => row);
const kept: string[] = ['a', '', 'b'].flatMap((value) =>
  value ? [value.toUpperCase()] : [],
);

代码示例

// flatMap maps and flattens exactly ONE element level, and the types agree.
const rows: number[][] = [[1, 2], [], [3, 4]];
const numbers: number[] = rows.flatMap((row) => row);
console.log('one level:', numbers);

// Triple-nested arrays lose only one layer per call
const deep: number[][][] = [[[1, 2]], [[3]]];
const once: number[][] = deep.flatMap((group) => group);
console.log('still nested:', JSON.stringify(once));

// Branches return arrays, so the element type U stays consistent
const labels: string[] = rows.flatMap((row) =>
  row.length === 0 ? ['empty row'] : row.map((n) => String(n)),
);
console.log('labels:', labels);

// Map-and-skip in one pass: return [] to drop an element
const kept: string[] = ['a', '', 'b'].flatMap((value) =>
  value ? [value.toUpperCase()] : [],
);
console.log('kept:', kept);