关于JavaScript可选链操作符(?.)作用的技术问询
关于JavaScript可选链操作符(?.)作用的技术问询
嘿,这个跟在data后面的问号是可选链操作符(Optional Chaining Operator),是ES2020新增的超实用语法糖,专门帮你解决访问嵌套对象/属性时的报错难题!
举个最直观的对比:
如果直接写data.name,一旦data是null或者undefined(比如接口请求失败返回空、变量没初始化),浏览器会直接抛出TypeError: Cannot read properties of undefined (reading 'name'),直接打断代码执行。
但用data?.name就完全不一样:
- 当
data存在(不是null/undefined)时,它就和普通的data.name一样,返回对应属性值; - 当
data不存在时,它会直接返回undefined,不会抛出任何错误,代码能继续往下走。
这在处理不确定结构的数据时特别好用,比如接口返回的嵌套数据:
// 模拟接口可能返回空数据 const userData = fetchUserInfo().then(res => res.data); // 这里userData可能是null // 不用可选链,得写冗长的判断 const userName = userData && userData.name; // 用可选链,代码简洁又安全 const userName = userData?.name;
另外它还支持更多场景:
- 访问数组元素:
arr?.[2](如果arr不存在就返回undefined) - 调用可能不存在的函数:
func?.()(如果func不是函数就不执行,返回undefined)
备注:内容来源于stack exchange,提问作者TheDeveloperFrontend




