如果检查属性时对象不存在,则返回undefined

时间:2020-06-10 11:17:01

标签: javascript

默认行为是尝试访问不存在的对象的属性是因为它会生成错误:

console.log(organization.name)
如果未定义组织,

将生成错误。是否有办法以某种方式更改此默认行为,并在尝试访问不存在的对象的属性时仅接收未定义的内容?有时,这可能会有用,而不是记住检查对象是否已定义

2 个答案:

答案 0 :(得分:2)

您可以使用可选链接

Optional chaining

可选链接运算符?.允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。

const organization = undefined; 
console.log(organization?.name);

答案 1 :(得分:2)

有多种解决方案:

使用Optional Chaining或“我喜欢新功能,或者我正在使用Babel”方法:

尽管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") },或使用“沿物业的方式”:

如果该值伪造(如&&organizationundefined等),则返回null的值,或者返回false否则。

organization.name