2021 / 09 / 16
可选链操作符与空值合并运算符
可选链操作符
可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空( nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined。
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
// 可选链和表达式
const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined
// 可选链与函数调用
console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined
用可选链操作符去操作就不会直接报错
- 避免使用一堆
&&操作符
// 之前你是这么操作的
const { foo = {} } = props.obj;
return <div>{foo.count && <Count/>}</div>
// 现在可以这样操作
const { foo = {} } = props.obj;
return <div>{props?.obj?.foo?.count && <Count/>}</div>
- 连用可选链操作符
可以连续使用可选链读取多层嵌套结构
let customer = {
name: "Carl",
details: {
age: 82,
location: "Paradise Falls" // details 的 address 属性未有定义
}
};
let customerCity = customer.details?.address?.city;
// … 可选链也可以和函数调用一起使用
let duration = vacations.trip?.getTime?.();
空值合并操作符
空值合并操作符(??)是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。
let customer = {
name: "Carl",
details: { age: 82 }
};
let customerCity = customer?.city ?? "暗之城";
console.log(customerCity); // “暗之城”
与逻辑或操作符(||)不同,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。也就是说,如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,'' 或 0)时。见下面的例子。
const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"
const baz = 0 ?? 42;
console.log(baz);
// expected output: 0
然而,由于 || 是一个布尔逻辑运算符,左侧的操作数会被强制转换成布尔值用于求值。任何假值(0, '', NaN, null, undefined)都不会被返回。这导致如果你使用0,''或NaN作为有效值,就会出现不可预料的后果。
let count = 0;
let text = "";
let qty = count || 42;
let message = text || "hi!";
console.log(qty); // 42,而不是 0
console.log(message); // "hi!",而不是 ""