javascript编程提效的两个操作符

85 阅读1分钟

可选链操作符

可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是undefined。

const adventurer = {  name: 'Alice',  cat: {    name: 'Dinah'  }};const dogName = adventurer.dog?.name;console.log(dogName);// expected output: undefined

空值合并操作符

空值合并操作符可以在使用可选链时设置一个默认值,保证常量不为 null 或者 undefined:

let customer = {  name: "Carl",  details: { age: 82 }};let customerCity = customer?.city ?? "暗之城";console.log(customerCity); // “暗之城”