默认行为是尝试访问不存在的对象的属性是因为它会生成错误:
console.log(organization.name)
如果未定义组织,将生成错误。是否有办法以某种方式更改此默认行为,并在尝试访问不存在的对象的属性时仅接收未定义的内容?有时,这可能会有用,而不是记住检查对象是否已定义
答案 0 :(得分:2)
您可以使用可选链接
可选链接运算符?.
允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。
const organization = undefined;
console.log(organization?.name);
答案 1 :(得分:2)
有多种解决方案:
尽管not supported by all browsers,但可选的链接是最干净的解决方案。如果需要回溯兼容性,则应该使用Babel或其他一些编译器。
order in layer
let organization = undefined
console.log(organization?.name)
organization = {name: "foo"}
console.log(organization?.name)
,或“有效或无效”的方式:此解决方案仅尝试显示try / catch
,或在失败的情况下执行organization.name
块。
catch
let organization = undefined
try {
console.log(organization.name)
} catch(e) {
console.log("organization.name cannot be accessed") // We end up here
}
organization = {name: "foo"}
try {
console.log(organization.name) // We end up here
} catch(e) {
console.log("organization.name cannot be accessed")
}
,或使用“沿物业的方式”:如果该值伪造(如&&
,organization
,undefined
等),则返回null
的值,或者返回false
否则。
organization.name