【问题标题】:Return undefined if object doesn't exist upon checking properties [duplicate]如果在检查属性时对象不存在,则返回 undefined [重复]
【发布时间】:2020-06-10 11:17:01
【问题描述】:

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

console.log(organization.name)

如果组织未定义,将产生错误。有没有办法以某种方式更改此默认行为,并在尝试访问不存在对象的属性时收到 undefined ?有时它比记住检查对象是否已定义更有帮助

【问题讨论】:

标签: javascript


【解决方案1】:

您可以使用可选链接

Optional chaining

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

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

【讨论】:

    【解决方案2】:

    有多种解决方案:

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

    尽管not supported by all browsers,可选的链接是最干净的解决方案。不过,如果您需要复古兼容性,则应该使用 Babel 或其他一些转译器。

    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 是假的(如undefinednullfalse、...),则返回organization 的值,否则返回organization.name

    let organization = undefined
    
    console.log(organization && organization.name) // `organization` is falsy, it will show its value
    
    organization = {name: "foo"}
    
    console.log(organization && organization.name) // `organization` is truthy, it will show `organization.name`

    【讨论】:

    • 非常感谢您的详细解答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    相关资源
    最近更新 更多