可选链(?.)和空值合并(??)简化嵌套属性访问与默认值设置,避免 TypeError 并提升代码可读性,适用于处理可能为 null 或 undefined 的情况,需注意兼容性及合理使用场景。

JS 可选链与空值合并,简单说,就是让你在访问嵌套对象属性时,不用写一堆
&&
null
undefined
使用可选链(
?.
??
TypeError: Cannot read properties of undefined
解决方案:
可选链(Optional Chaining):?.
可选链允许你安全地访问嵌套对象的属性,即使中间的属性不存在,也不会报错,而是返回
undefined
例如,假设你有这样一个对象:
const user = {
profile: {
address: {
city: 'Beijing'
}
}
};如果直接访问
user.profile.address.street
user.profile
user.profile.address
const street = user?.profile?.address?.street; // street 为 undefined,不会报错 console.log(street);
如果
user
null
undefined
undefined
在函数调用中使用可选链:
const result = someObject?.someMethod?.(); // 如果 someObject 或 someMethod 不存在,result 为 undefined
空值合并运算符(Nullish Coalescing Operator):??
空值合并运算符
??
null
undefined
||
||
falsy
0
''
false
例如:
const name = localStorage.getItem('name') ?? 'Guest'; // 如果 localStorage 中没有 'name',则 name 为 'Guest'
const count = 0 ?? 10; // count 为 0,因为 0 不是 null 或 undefined
const value = null ?? 'default'; // value 为 'default'使用场景:
0
''
null
undefined
组合使用:
可以将可选链和空值合并运算符组合使用,以更优雅地处理嵌套对象属性的访问和默认值设置。
const city = user?.profile?.address?.city ?? 'Unknown'; // 如果 city 不存在,则 city 为 'Unknown'
传统的 JavaScript 代码在访问深层嵌套对象属性时,需要进行大量的
&&
TypeError
let city;
if (user && user.profile && user.profile.address) {
city = user.profile.address.city;
} else {
city = 'Unknown';
}这样的代码冗长且难以阅读。可选链和空值合并运算符的出现,简化了代码,提高了可读性,同时也减少了出错的可能性。它们主要解决了以下问题:
TypeError
if
&&
可选链和空值合并运算符是 ES2020 引入的新特性。这意味着,在一些较旧的浏览器或 Node.js 环境中,可能无法直接使用。
兼容性解决方案:
@babel/plugin-proposal-optional-chaining
@babel/plugin-proposal-nullish-coalescing-operator
示例 Babel 配置:
{
"plugins": [
"@babel/plugin-proposal-optional-chaining",
"@babel/plugin-proposal-nullish-coalescing-operator"
]
}0
''
示例代码 (TypeScript):
interface User {
profile?: {
address?: {
city?: string;
};
};
}
const getUserCity = (user: User): string => {
return user?.profile?.address?.city ?? 'Unknown';
};
const myUser: User = {};
console.log(getUserCity(myUser)); // 输出 "Unknown"
const myUser2: User = { profile: { address: { city: 'Shanghai' } } };
console.log(getUserCity(myUser2)); // 输出 "Shanghai"总之,可选链和空值合并运算符是 JavaScript 中非常有用的特性,可以提高代码的可读性、安全性和简洁性。但需要注意兼容性问题,并根据实际情况谨慎使用。
以上就是JS 可选链与空值合并 - 简化多层对象属性访问的安全写法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号