?. 称为可选链接运算符 (TC39 Stage 4),当您不确定嵌套属性是否存在时使用。如果您尝试使用. 运算符来访问undefined 的属性,您会得到TypeError。
例如:
const obj = {foo: {} };
//This is safe, results in undefined
console.log(obj?.foo?.bar?.baz);
//This results in Uncaught TypeError: Cannot read property 'baz' of undefined
console.log(obj.foo.bar.baz);
?? 被称为空合并运算符 (TC39 Stage 3)。当您使用空字符串"" 或带有|| 运算符的0 等虚假值时,|| 右侧的操作数将被返回,因为虚假值被忽略。
?? 当您不想要它并且实际上您想考虑虚假值时会派上用场。如果左侧的值为null 或undefined,则仅采用?? 右侧的值:
例如:
const empString = "";
const defaultValue = empString || "A default value";
//Outputs A default value as "" empty string is falsy
console.log(defaultValue);
const actualValue = empString ?? "A default value";
//Does not print the default value as the empString is neither null or undefined
console.log(actualValue);
与0、false 等其他虚假值相同,与将输出'default 字符串的|| 运算符不一致:
console.log(false ?? 'default') //false
console.log(0 ?? 'default') // 0
仅适用于undefined 和null,这将输出与|| 运算符一致提供的默认值:
console.log(undefined ?? 'default') //default
console.log(null ?? 'default') //default