JavaScript 中 ||、?.、?? 的含义与用法
一、符号概览
- || 逻辑或 :返回第一个"真值"(truthy);若都是"假值"(falsy),返回最后一个值。常用于提供默认值与布尔判断。falsy 值包括:false、0、""、null、undefined、NaN。
- ?. 可选链 :安全访问嵌套属性或调用方法;当链中某项为 null/undefined 时,表达式短路返回 undefined 而不报错。
- ?? 空值合并 :仅当左侧为 null/undefined 时返回右侧默认值;对 0、""、false 等"假值"会原样保留。
- 相关扩展:??= 空值合并赋值(仅在左侧为 null/undefined 时赋值)。
二、用法与示例
-
|| 逻辑或
-
规则:返回第一个真值;具有短路特性(左侧为真不再求值右侧)。
-
示例:
jsconst a = 0 || 10; // 10(0 是 falsy) const b = "" || "Hi"; // "Hi"(空字符串是 falsy) const c = null || "def"; // "def" -
场景:需要把任何 falsy 都替换成默认值的快捷写法。
-
-
?. 可选链
-
规则:访问 obj?.prop 、obj?.[expr] 、arr?.[index] 、func?.() 时,若左侧为 null/undefined 则短路返回 undefined。
-
示例:
jsconst user = { profile: { name: "A" } }; console.log(user?.profile?.age); // undefined console.log(user.settings?.theme); // undefined console.log(user.profile.getName?.()); // undefined(方法不存在不报错) -
场景:处理 API 深层结构、可能缺失的属性/方法,避免 Cannot read property... 错误。
-
-
?? 空值合并
-
规则:仅当左侧为 null/undefined 时返回右侧;其他值(含 0、""、false)保留。
-
示例:
jsconst a = 0 ?? 10; // 0(保留 0) const b = "" ?? "Hello"; // ""(保留空字符串) const c = null ?? "def"; // "def" const d = false ?? true; // false(保留 false) -
场景:需要区分"未设置(null/undefined)"与"显式假值(0、""、false)"的默认值逻辑。
-
三、如何选择
- 需要安全访问可能为 null/undefined 的深层属性或方法:用 ?.。
- 只想在值为 null/undefined 时给默认值,同时保留 0、""、false :用 ??。
- 希望把所有 falsy (如 0、""、false )都替换成默认值:用 ||。
- 需要"仅当缺失才赋值"的简写:用 ??=。
四、组合与注意
-
常见组合:先安全取值,再给默认值,避免报错与误覆盖。
jsconst city = user?.address?.city ?? "未知城市"; -
与运算优先级:表达式中混用 ?? 与 &&/|| 必须用括号明确顺序,否则语法错误。
js// 错误:let x = a && b ?? c; let x = (a && b) ?? c; // 正确 -
不能对可选链左侧直接赋值:
jsobj?.prop = 1; // SyntaxError -
浏览器/环境支持提示:?. 与 ?? 为 ES2020 特性;如需兼容旧环境,请使用 Babel 等转译工具。