实现说明
全部逻辑都在函数 concatAll中。
使用要点
- 跑完文件,输出里会留下标记——
object spread of null:、array spread of null threw:、merged with null override:。
常见问题
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。 文件在加载时定义 concatAll。
签名一览:function concatAll(lists)
核心语句
return lists.reduce((acc, list) => acc.concat(list ?? []), []);
代码示例
// The asymmetry: object spread silently skips null and undefined sources,
// while array spread throws on them
console.log('object spread of null:', { retries: 3, ...null, ...undefined });
try {
const items = [...null];
console.log('array spread ok:', items);
} catch (err) {
console.log('array spread of null threw:', err.constructor.name);
}
// config merging therefore needs no null guard for object layers
const base = { host: 'localhost', port: 8080, retries: 3 };
const override = null; // absent layer
const merged = { ...base, ...override };
console.log('merged with null override:', merged);
console.log('layered:', { ...base, ...undefined, retries: 1 });
// arrays and iterables DO need a nullish guard before spreading
function concatAll(lists) {
return lists.reduce((acc, list) => acc.concat(list ?? []), []);
}
console.log('concat with nullish entry:', concatAll([[1, 2], null, [3]]));
// Array.from on a nullish value throws too, unless you coalesce first
console.log('Array.from(null ?? []):', Array.from(null ?? []));
try {
Array.from(null);
} catch (err) {
console.log('Array.from(null) threw:', err.constructor.name);
}