运算符
??
空值合并运算符
当左侧操作数为 null
或 undefined
时,返回右侧操作数,否则返回左侧操作数。
我通常用来代替三目运算符和逻辑或运算符。
const foo = doSomething() ?? "defaultValue";
// 三目运算符太繁琐
const res = doSomething();
const foo = res === undefined ? res : "defaultValue";
// 逻辑或运算符在左侧操作数为假值(例如 '',0)时会不符合预期
const doSomething = () => "";
const foo = doSomething() || "defaultValue"; // 'defaultValue'
?.
可选链操作符
可选链运算符允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。它的短路返回值是 undefined
。
我通常用来代替 try catch
const foo = "foo";
JSON.parse(foo?.bar?.baz?.()); // 报错,因为 undefined 不是合法的 json string
JSON.parse(foo?.bar?.baz?.() ?? null); // null
??=
逻辑空赋值
仅在 x 是空值(null 或 undefined)时对其赋值。