【问题标题】:Cannot check for null if the object is null ("cannot read the property" error)如果对象为空,则无法检查空值(“无法读取属性”错误)
【发布时间】:2022-12-17 03:34:00
【问题描述】:

我只是想不出如何解决一个简单的情况:当我的 JSON 数据返回一个其属性之一为空的对象时,我只是找不到一种方法来检查它,因为即使在检查本身时,也会抛出异常:

var data=Template.currentData();  //here the RECORD property is an empty string, ""

if(!data.record)   //throws an error, cannot read null of 'record'

当我根本无法读取属性时,如何执行检查?

【问题讨论】:

    标签: javascript null


    【解决方案1】:

    使用optional chaining

    var data=Template?.currentData?.();
    
    if(!data?.record)
    

    演示:

    const Template = "string without currentData property"
    
    var data=Template?.currentData?.();
    
    if(!data?.record){
      console.log("no record prop")
    }

    【讨论】:

      【解决方案2】:

      在读取record 值之前,您应该检查data 值不为空。所以试试这个

      if(data && !data.record)  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-15
        • 2020-10-24
        • 1970-01-01
        • 2012-12-18
        • 2021-09-26
        • 1970-01-01
        • 1970-01-01
        • 2017-06-05
        相关资源
        最近更新 更多