繁体   English   中英

如果对象为 null(“无法读取属性”错误),则无法检查 null

[英]Cannot check for null if the object is null ("cannot read the property" error)

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

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

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

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

使用可选链接

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") }

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

if(data && !data.record)  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM