# 一、可选链操作符
# 1. 开始
可选链操作符(?.
)允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。
?.
操作符的功能类似于.
链式操作符,不同之处在于,在引用为空(nullish
) (null
或者undefined
)的情况下不会引起错误,该表达式短路返回值是undefined
。
与函数调用一起使用时,如果给定的函数不存在,则返回undefined
。
# 2. 语法
obj?.prop // 访问对象属性
obj?.[expr] // 表达式,如 `let nestedProp = obj?.['prop' + 'Name'];`
arr?.[index] // 访问数组索引
func?.(args) // 访问不确定存在的方法
# 3. 例子
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
# 4. 使用空值合并操作符
空值合并操作符可以在使用可选链时设置一个默认值:
let customer = {
name: "Carl",
details: { age: 82 }
};
let customerCity = customer?.city ?? "暗之城";
console.log(customerCity); // “暗之城”
# 5. 兼容性
支持情况:Chrome 80+
,Firefox 72+
,Safari in IOS 13.4+
,IE
不支持
# 二、空值合并操作符
空值合并操作符(??
)是一个逻辑操作符,当左侧的操作数为null
或者undefined
时,返回其右侧操作数,否则返回左侧操作数。
与逻辑或操作符(||
)不同,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。也就是说,如果使用||
来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,''
或0
)时。
# 1. 例子
const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"
const baz = 0 ?? 42;
console.log(baz);
// expected output: 0
# 2. 兼容性
支持情况:Chrome 80+
,Firefox 72+
,Safari in IOS 13.4+
,IE
不支持