es新增运算符
?? ( 空值合并运算符) ?. (可选链式运算符) ??= (空值合并赋值操作符)
// ?? ( 空值合并运算符):这个运算符主要是左侧为null和undefined,直接返回右侧值
let result = value ?? '默认值';
. ??(空值合并运算符)
✅ 用于防止 null 和 undefined,不会影响 false、0、''(空字符串)。
let value = null;
let result = value ?? "默认值"; // value 为 null 或 undefined,返回 "默认值"
console.log(result); // 输出: "默认值"
let value2 = 0;
let result2 = value2 ?? "默认值"; // 0 不是 null 或 undefined,所以返回 0
console.log(result2); // 输出: 0
2. ?.(可选链运算符)
✅ 用于安全访问对象属性,防止 undefined 或 null 时报错
const obj = null;
let prop = obj?.property; // obj 是 null,不会报错,而是返回 undefined
console.log(prop); // undefined
const user = { name: "Tom", address: { city: "New York" } };
console.log(user?.address?.city); // "New York"
console.log(user?.contact?.phone); // contact 不存在,返回 undefined,不会
??=
(空值合并赋值操作符)
✅ 只有变量为 null
或 undefined
时,才会赋值
let x = null; x ??= 5; // x 为 null,所以赋值为 5 console.log(x); // 5 let y = 0; y ??= 10; // y 是 0(不是 null 或 undefined),所以不赋值 console.log(y); // 0