在JavaScript中,?. 被称为可选链操作符(Optional Chaining Operator)。它允许你访问对象的深层属性而不必显式地检查每一层属性是否存在。如果链中的某个属性不存在,表达式将短路返回undefined,而不是抛出一个TypeError异常。
例如,假设你有一个对象a,它可能包含一个属性b,而b又可能包含属性c:
const a = {b: {c: 1}
};
使用传统的访问方式,你需要这样检查属性:
const c = a && a.b && a.b.c;
但是使用可选链操作符,你可以简化为:
const c = a?.b?.c;
如果a、a.b或a.b.c中的任何一个不存在,c将被赋值为undefined,而不是抛出错误。这使得代码更加简洁和安全。可选链操作符也可以与函数调用和new操作符一起使用:
const result = a?.b?.doSomething();
const instance = new a?.b?.MyClass();
如果a.b或a.b.MyClass不存在,result和instance将分别是undefined和TypeError(因为new操作符需要一个有效的构造函数)。
面试题:
const person = {firstName: "Lydia",lastName: "Hallie",pet: {name: "Mara",breed: "Dutch Tulip Hound"},getFullName() {return `${this.firstName} ${this.lastName}`;}
};console.log(person.pet?.name);
console.log(person.pet?.family?.name);
console.log(person.getFullName?.());
console.log(person.getLastName?.());
输出是:Mara undefined Lydia Hallie undefined