[英]Not sure what's wrong with this JavaScript “undefined” check
I thought I had correctly followed the recommendations in this question for checking undefined
: 我以为我已正确遵循此问题中的建议来检查
undefined
:
if(typeof window.session.location.address.city != "undefined")
console.log(window.session.location.address.city);
But the code above generates this error: 但是上面的代码会产生此错误:
Uncaught TypeError: Cannot read property 'city' of undefined
What's the correct way to perform this check? 进行此检查的正确方法是什么?
address
is undefined so you can't read its property city
address
不确定,因此您无法读取其物业city
You'll have to check that address
is defined first. 您必须检查是否首先定义了
address
。
Check for the existence of each property: 检查每个属性是否存在:
if (window.session && session.location && session.location.address)
console.log(session.location.address.city);
That may log undefined
, but will not result in an error. 这可能会记录
undefined
,但不会导致错误。 If you only want to log city
if it is not undefined
, just add in a && typeof session.location.address.city != "undefined"
. 如果你只是想记录
city
,如果它不是 undefined
,只是添加在&& typeof session.location.address.city != "undefined"
。 We use typeof
in this case because if city
contains an empty string or null
, it will also evaluate to false
(ie, it is "falsey"). 在这种情况下,我们使用
typeof
,因为如果city
包含一个空字符串或null
,它也将评估为false
(即,它为“ falsey”)。 Of course, if you only want to log city
if it has a value, leave off the typeof
and just check to see if it evaluates to true
(ie, it is "truthy") the same way as the others. 当然,如果您只想记录具有值的
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.