[英]Not sure what's wrong with this JavaScript “undefined” check
我以为我已正确遵循此问题中的建议来检查undefined
:
if(typeof window.session.location.address.city != "undefined")
console.log(window.session.location.address.city);
但是上面的代码会产生此错误:
Uncaught TypeError: Cannot read property 'city' of undefined
进行此检查的正确方法是什么?
address
不确定,因此您无法读取其物业city
您必须检查是否首先定义了address
。
检查每个属性是否存在:
if (window.session && session.location && session.location.address)
console.log(session.location.address.city);
这可能会记录undefined
,但不会导致错误。 如果你只是想记录city
,如果它不是 undefined
,只是添加在&& typeof session.location.address.city != "undefined"
。 在这种情况下,我们使用typeof
,因为如果city
包含一个空字符串或null
,它也将评估为false
(即,它为“ falsey”)。 当然,如果您只想记录具有值的city
,请忽略typeof
然后检查它是否与其他方法一样评估为true
(即,它是“真实的”)。
if(typeof window.session.location.address === 'undefined')
alert("address is undefined!");
else
console.log(window.session.location.address.city);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.