空值合并操作符(??)
是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。
let person = {
profile: {
name: "",
age: 0
}
};
console.log(person.profile.name || "Anonymous"); // Anonymous
console.log(person.profile.age || 18); // 18
我们可以使用??操作符来代替||,使其类型更严格一些,这只允许在值为null或undefined时使用默认值。
console.log(person.profile.name ?? "Anonymous"); // ""
console.log(person.profile.age ?? 18); // 0
可选链操作符( ?. )
与合并空操作符类似,JavaScript在处理错误值时可能无法按我们希望的方式工作。如果我们想要的是未定义的,我们可以返回一个值,但是如果到它的路径是未定义的呢?通过在.之前添加一个问号,我们可以使值的路径的任何部分成为可选的,这样我们仍然可以与它交互。
let person = {};
console.log(person.profile.name ?? "Anonymous"); // person.profile is undefined
console.log(person?.profile?.name ?? "Anonymous");
console.log(person?.profile?.age ?? 18);
传递门:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/%E5%8F%AF%E9%80%89%E9%93%BE