JavaScript flatMap 实战:一对多转换、空槽与共享引用
列表转换不总是一进一出:一条内容可能生成多个标签条目,关闭的记录则不应进入结果。flatMap 适合表达这种“每项决定贡献多少结果”的规则。它让回调先产出值,再将其中的数组展开一层;不要把它当成无限递归的拍平工具。下面用一条标签导出流水线和可运行断言,把容易混淆的边界拆开。

先决定一条输入贡献多少项
返回空数组表示不贡献结果,返回单元素数组表示贡献一项,返回多元素数组则依序加入多项。这里减少的是结果数量,不是从源数组删除元素。直接返回一个非数组值也会贡献一项,因此返回 undefined 与返回空数组不同:前者保留一个明确的 undefined,后者不占位置。
“一层”针对回调返回的数组。例如返回 [n, inner] 时,n 和 inner 进入新结果;若 inner 自己还是数组,它仍作为整体存在,内部的空槽也不会在这一轮被继续处理。ECMAScript 的 flatMap 算法将展开深度设为 1,这是判断嵌套结果的依据。
空槽与非数组,不能靠外观判断
源数组缺失的索引通常不会调用回调;回调返回数组中的空槽,会在这一层展开时跳过。两者发生在不同位置。显式写入的 undefined 则是存在的元素,会被处理或保留。更精确地说,算法检查属性是否存在,原型链上的同名数字属性也算存在,不能将“没有自有属性”直接等同于必然跳过。
返回值是否展开取决于它是不是数组,不取决于是否有 length、是否可迭代或是否长得像数组。字符串、类型化数组和带数字键的普通对象都作为单项加入,设置 Symbol.isConcatSpreadable 也不会把普通对象变成这里的数组。下方测试同时检查内容和对象身份,避免只打印外观得出结论。对应说明可查 MDN flatMap 文档。
索引来自输入,共享引用仍需留意
回调拿到的 index 属于当前调用 flatMap 的源数组,不会随着前面丢弃或扩展元素而改成结果索引;第三个参数同样是这个源,而不是正在构造的结果。如果前面先执行 filter,这里的源就是过滤后的数组。需要追溯最初数据时,应像示例一样在合适的阶段显式记录索引。
普通数组调用会生成新数组,方法本身不改写源数组结构,但回调完全可以自行修改源。输出中的对象也不自动深拷贝,多个位置可能指向同一对象。第七组先验证源结构未变,再修改输出对象来证明引用共享;第十组另测回调追加元素,展示迭代长度在开始时读取,追加项不会因此获得本轮回调。
完整脚本:标签导出与十二组边界测试
buildLines 只接收数组,跳过关闭、缺少有效编号或标签格式错误的记录,再把有效字符串标签去掉首尾空白,形成可导出的独立条目。这里保留原输入索引,便于定位问题记录;规则不去重、不改大小写,也不承担完整业务校验。对于外部输入,应在入口额外检查整个 records 的类型和业务约束。
将下面完整代码保存为 test_flatmap.cjs,分别执行 node test_flatmap.cjs 与 node --unhandled-rejections=strict test_flatmap.cjs。本文实测运行时为 Node.js v24.19.0,两次各通过 12 组,进程退出码均为 0。严格拒绝模式只是第二次执行配置,并不代表 flatMap 会等待异步回调;本文脚本全部使用同步回调。
'use strict';
const assert = require('node:assert/strict');
let groups = 0;
function test(name, run) {
run();
groups += 1;
console.log(`PASS ${groups}: ${name}`);
}
// Export-ready lines from trusted in-memory records, not network input.
function buildLines(records) {
return records.flatMap((record, sourceIndex) => {
if (!record || record.enabled !== true ||
typeof record.id !== 'string' || !record.id.trim() ||
!Array.isArray(record.tags)) return [];
return record.tags.flatMap((tag) => {
if (typeof tag !== 'string' || !tag.trim()) return [];
return [{ id: record.id.trim(), tag: tag.trim(), sourceIndex }];
});
});
}
test('one level only; deeper array and its hole survive', () => {
const inner = [9, , 10];
const out = [1].flatMap((n) => [n, inner]);
assert.deepEqual(out, [1, [9, , 10]]);
assert.equal(out[1], inner);
assert.equal(1 in out[1], false);
});
test('zero, one, or multiple output values', () => {
const out = [-1, 4, 5].flatMap((n) => {
if (n < 0) return [];
return n % 2 === 0 ? [n] : [n, n + 1];
});
assert.deepEqual(out, [4, 5, 6]);
});
test('source holes are skipped, explicit undefined is visited', () => {
const source = [3, , undefined, 7];
const seen = [];
const out = source.flatMap((value, index) => {
seen.push(index);
return [value];
});
assert.deepEqual(seen, [0, 2, 3]);
assert.deepEqual(out, [3, undefined, 7]);
assert.equal(1 in out, true);
});
test('returned holes are skipped, explicit undefined remains', () => {
const out = [2, 5].flatMap((n) => [, n, , undefined]);
assert.deepEqual(out, [2, undefined, 5, undefined]);
assert.deepEqual(Object.keys(out), ['0', '1', '2', '3']);
});
test('non-arrays stay whole, including spreadable array-like objects', () => {
const like = { 0: 'a', length: 1, [Symbol.isConcatSpreadable]: true };
const typed = new Uint8Array([2, 3]);
const values = [like, typed, 'xy', null, undefined];
const out = values.flatMap((value) => value);
assert.deepEqual(out, values);
assert.equal(out[0], like);
assert.equal(out[1], typed);
assert.equal(out.length, 5);
});
test('indices and third argument belong to the current source', () => {
const source = ['drop', 'double', 'keep'];
const seen = [];
const out = source.flatMap((value, index, array) => {
assert.equal(array, source);
seen.push(index);
return value === 'drop' ? [] : value === 'double' ? [index, index] : [index];
});
assert.deepEqual(seen, [0, 1, 2]);
assert.deepEqual(out, [1, 1, 2]);
});
test('new array, unchanged source structure, shared object references', () => {
const item = { count: 1 };
const source = [item];
const out = source.flatMap((value) => [value, value]);
assert.notEqual(out, source);
assert.deepEqual(source, [{ count: 1 }]);
assert.equal(source.length, 1);
assert.equal(out[0], source[0]);
assert.equal(out[0], out[1]);
out[0].count = 8;
assert.equal(source[0].count, 8);
});
test('generic receiver uses length and sees inherited index properties', () => {
const source = Object.assign(Object.create({ 1: 6 }), {
0: 4, 3: 99, length: 3
});
const seen = [];
const out = Array.prototype.flatMap.call(source, (value, index, array) => {
assert.equal(array, source);
seen.push(index);
return [value * 2];
});
assert.deepEqual(seen, [0, 1]);
assert.deepEqual(out, [8, 12]);
});
test('regular callback receives thisArg', () => {
const out = [2, 3].flatMap(function (n) {
return [n * this.factor];
}, { factor: 10 });
assert.deepEqual(out, [20, 30]);
});
test('callback may mutate source; iteration length is read at start', () => {
const source = [1, 2];
const seen = [];
const out = source.flatMap((value, index, array) => {
seen.push(index);
if (index === 0) array.push(3);
return [value];
});
assert.deepEqual(source, [1, 2, 3]);
assert.deepEqual(seen, [0, 1]);
assert.deepEqual(out, [1, 2]);
});
test('invalid callback and callback error both propagate', () => {
assert.throws(() => [].flatMap(null), TypeError);
const error = new Error('stop');
assert.throws(() => [1].flatMap(() => { throw error; }),
(caught) => caught === error);
});
test('practical pipeline keeps source trace and does not alter records', () => {
const records = [
{ id: ' post-a ', enabled: true, tags: [' JS ', '', null, 'Node'] },
{ id: 'post-b', enabled: false, tags: ['draft'] },
null,
{ id: 'post-c', enabled: true, tags: [' Web '] },
{ id: 'post-d', enabled: true, tags: 'invalid' },
{ id: ' ', enabled: true, tags: ['skip'] }
];
const before = structuredClone(records);
const lines = buildLines(records);
assert.deepEqual(lines, [
{ id: 'post-a', tag: 'JS', sourceIndex: 0 },
{ id: 'post-a', tag: 'Node', sourceIndex: 0 },
{ id: 'post-c', tag: 'Web', sourceIndex: 3 }
]);
assert.deepEqual(records, before);
assert.deepEqual(buildLines([]), []);
console.log('PIPELINE', JSON.stringify(lines));
});
assert.equal(groups, 12);
console.log(`OK: ${groups} groups; runtime ${process.version}`);读懂结果,再放进业务代码
流水线最终得到 post-a 的 JS、Node 两项和 post-c 的 Web 一项,来源索引分别是 0、0、3。测试还覆盖普通 thisArg、借用方法处理类数组、无效回调及异常传播。选择 flatMap 的理由应是零到多项转换更清楚;本文没有性能基准,也没有把单一 Node 环境的通过结果当成浏览器兼容承诺。
资料核验日期:2026 年 10 月 21 日。规范中的 FlattenIntoArray 算法还给出了属性检查、数组判定和逐项写入的细节,适合在遇到特殊对象时进一步核对。

