簡體   English   中英

不確定此JavaScript“未定義”檢查出了什么問題

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM