2016-10-04 19 views
0

帶賓語這樣檢查在Javascript中嵌套的對象的字段definedness

book.chapter.paragraph.sentence.word 

假設要檢索某個詞

book[6][3][15][3] 

是某些引用現有的一句話,你真的必須執行這樣的檢查...

if(typeof book[6] !== "undefined" && typeof book[6][3] !== "undefined" && typeof book [6][3][15] !== "undefined" && typeof book[6][3][15][3] !== "undefined") ... 

...還是有更好的方法嗎?

回答

0

通常爲了動態訪問嵌套屬性,您需要進行迭代檢查。但是,您也可以使用try catch並解析錯誤消息以訪問未定義的屬性。如

try{ 
 
var book = {page111: {paragraph2:{sentence4:{word12:"test"}}}}; 
 
    list = ["page112","paragraph2","sentence4","word12"], 
 
    word = book[list[0]][list[1]][list[2]][list[3]]; 
 
    console.log(word); 
 
}catch(e){console.log(list[list.indexOf(e.message.match(/\'(.*)\'/)[1])-1], "is undefined")}

我不得不承認,這是很醜陋的。

+0

你說預計會進行迭代檢查:事實上,這是我的第一個想法。我認爲這將是一個殘酷的解決方案,但如果這是你所暗示的規範,我會爲此而努力。我認爲這種迭代檢查可能有一個內置函數,我不知何故失蹤... – resle

相關問題