簡體   English   中英

使用typeof檢查變量是否未定義

[英]using typeof to check if a variable is not undefined

為什么typeof不檢查以下代碼段是否未定義變量:

 if(typeof res.data.data[1].name !== undefined){
//the idea is that if code gets here it means it contains some data
    .......
    }

通過上面的檢查,我仍然在if塊得到此結果

TypeError: Cannot read property 'name' of undefined

這可能是因為res.data.data為null,只需添加一個null檢查

if(res.data.data && typeof res.data.data[1].name !== undefined){

這是因為res.data.data[1]本身未定義。 我建議將您的病情擴大至:

const { data = [] } = res.data;
if (data[1] && typeof data[1].name !== 'undefined') {
  // Do somehing
}

另外,您的檢查是不正確的,因為您正在比較typeof結果與undefined同時它返回字符串,在這種情況下為'undefined'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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