






















||(逻辑或)规则:从左到右求值,返回第一个真值;如果所有操作数都为假,则返回最后一个操作数。
示例:
console.log(0 || 'hello' || false); // 'hello'(第一个真值)
console.log('' || null || 0); // 0(全是假,返回最后一个)
&&(逻辑与)规则:从左到右求值,返回第一个假值;如果所有操作数都为真,则返回最后一个操作数。
示例:
console.log(1 && 'hi' && null); // null(第一个假值)
console.log(1 && 'hi' && true); // true(全为真,返回最后一个)
??(空值合并运算符)规则:只有当第一个操作数是 null 或 undefined 时,才返回第二个操作数;否则返回第一个操作数。
注意:0、''、false 等都不算“空值”,不会触发返回右侧。
示例:
console.log(0 ?? 100); // 0(0 不是 null/undefined)
console.log(null ?? 100); // 100
console.log(undefined ?? 100); // 100
|| 会把 0、''、false 等视为假值,而 ?? 只认 null 和 undefined。
实践中常用 || 提供默认值(但会覆盖 0/'' 等有效值),用 ?? 更精确地处理缺失值。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。