← 中文资源

简体中文版本

展开运算符对 null 的双面行为

对象展开会静默跳过 null 与 undefined 来源,数组展开却直接抛 TypeError:合并配置层不需要判空,拼接列表必须先兜底,这个不对称值得记住。

阅读英文原文

运行结果

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

object spread of null: { retries: 3 }
array spread of null threw: TypeError
merged with null override: { host: 'localhost', port: 8080, retries: 3 }
layered: { host: 'localhost', port: 8080, retries: 1 }
concat with nullish entry: [ 1, 2, 3 ]
Array.from(null ?? []): []
Array.from(null) threw: TypeError

实现说明

全部逻辑都在函数 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);
}