← 中文资源

简体中文版本

假值在布尔上下文中塌缩

七个假值在布尔上下文里塌缩为 false,空数组空对象却意外为真;filter(Boolean) 一次清掉假值,|| 与 ?? 对缺失默认值的处理截然不同。

阅读英文原文

运行结果

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

Boolean(false) = false
Boolean(0) = false
Boolean(-0) = false
Boolean(0n) = false
Boolean('') = false
Boolean(null) = false
Boolean(undefined) = false
Boolean(NaN) = false
Boolean([]) = true
Boolean({}) = true
Boolean('0') = true
compacted: [ 'text', 42 ]
'' || 'anon' -> anon
'' ?? 'anon'  ->

实现说明

for (const [label, value] of falsy) 反复执行,循环体之外没有别的重复。 演示用的数据放在这几个模块级绑定中:falsy、mixed、input。

使用要点

  • 直接运行文件,输出会带上标签,比如 Boolean([]) =、Boolean(、compacted:——输出的每一行都能指回产生它的那次调用。

常见问题

有需要管理的依赖吗?

没有。无需声明或安装任何依赖。 状态都挂在模块顶层:falsy、mixed、input。

核心语句

const mixed = [0, 'text', null, 42, '', undefined, NaN, false];
const input = '';

代码示例

// Boolean contexts coerce any value to true or false.
// Only seven values are falsy; every other value is truthy.
const falsy = [
  ['false', false],
  ['0', 0],
  ['-0', -0],
  ['0n', 0n],
  ["''", ''],
  ['null', null],
  ['undefined', undefined],
  ['NaN', NaN],
];

for (const [label, value] of falsy) {
  console.log(`Boolean(${label}) = ${Boolean(value)}`);
}

// Surprises: empty arrays and objects are truthy despite looking empty.
console.log('Boolean([]) =', Boolean([]));
console.log('Boolean({}) =', Boolean({}));
console.log("Boolean('0') =", Boolean('0'));

// filter(Boolean) compacts falsy entries out of a list.
const mixed = [0, 'text', null, 42, '', undefined, NaN, false];
console.log('compacted:', mixed.filter(Boolean));

// || coerces for defaults, ?? only replaces null and undefined.
const input = '';
console.log("'' || 'anon' ->", input || 'anon');
console.log("'' ?? 'anon'  ->", input ?? 'anon');