2017-09-16 83 views
0

我做我的javascript代碼下面的JavaScript數組元素錯誤,同時訪問inspite有檢查

if(
    typeof player['stats'] != undefined && 
    typeof player['stats']['guild'] != undefined && 
    typeof player['stats']['guild']['master'] != undefined && 
    typeof player['stats']['guild']['master']['since'] != undefined 
) 

但是我得到錯誤:

Cannot read property 'since' of null

我一直堅持這樣的而。任何JavaScript大師能幫助我嗎?

+1

刪除'typeof's和'= undefined'部分! –

+0

使用'lodash#get'來簡化這種怪異的構造。 – alexmac

+0

@ibrahimmahrir沒有幫助:(更新:沒有看到你的編輯,讓我再試一次 –

回答

1

的typeof返回字符串,所以比較反對「未定義」

if(
    typeof player['stats'] != "undefined" && 
    typeof player['stats']['guild'] != "undefined" && 
    typeof player['stats']['guild']['master'] != "undefined" && 
    player['stats']['guild']['master'] != null && 
    typeof player['stats']['guild']['master']['since'] != "undefined" 
) 
+2

這仍然不能解決問題,因爲'player ['stats'] ['guild'] ['master']''null'not'undefined'(從錯誤中推導出來).. –

+0

這樣做沒有工作... –

+0

@ibrahimmahrir是錯過了,它將需要比較爲null,代碼更正,感謝您指向 – Dij

1

只是檢查值是否truthy:

if(
    player['stats'] && 
    player['stats']['guild'] && 
    player['stats']['guild']['master'] && 
    player['stats']['guild']['master']['since'] != undefined // only check the last one as it is probably not an object but another value such as 0 (depending on what your data looks like, if you have it as an object then just remove the != undefined check) 
) 
+1

如果玩家['stats'] ['guild'] ['master '] ['since']'具有_falsy_值(false,0,「」)? – alexmac

+0

@alexmac它主要是一個他將在'if'主體中使用的對象。但我已經添加了一個支票以防萬一。 –

0

你可以寫你傳遞對象一個相當簡單的對象getter函數然後用點分隔鍵找到這樣的值:

function getObj(obj, key) { 
    return key.split(".").reduce((acc, cur) => { 
    if (acc !== undefined) { 
     return acc[cur]; 
    } 
    return acc; 
    }, obj); 
} 

然後,您可以抓住t他看重你想看看它是否未定義或不:

const player = { 
    stats: { 
    guild: { 
     master: { 
     since: '2004' 
     } 
    } 
    } 
}; 

const since = getObj(player, 'stats.guild.master.since'); 
if (since) { 
    // do some code 
} 

這是你可以在任何物體上使用一個方便實用的功能,讓您的if語句更漂亮。

+0

我認爲這將工作,只有當你刪除'!== undefined'並將其添加到if語句中'if(since!== undefined)'因爲在他的情況下master是'null' – Slai

+0

已更新所以它優雅地處理null和未定義:https://jsfiddle.net/vhnoqo8u/ – jas7457

0

您也可以避免臨時變量的多次查找:

player = { stats: { guild: { master: null } } } 
 

 
if ((temp = player.stats) && 
 
    (temp = temp.guild) && 
 
    (temp = temp.master) && 
 
    (temp = temp.since) !== undefined)   
 
    console.log(true , temp) 
 
else 
 
    console.log(false, temp) 
 

 

 
player.stats.guild.master = { since: 'today' } 
 

 
if ((temp = player.stats) && 
 
    (temp = temp.guild) && 
 
    (temp = temp.master) && 
 
    (temp = temp.since) !== undefined)   
 
    console.log(true , temp) 
 
else 
 
    console.log(false, temp)