拿一个像这样的对象
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 :(得分:0)
通常,对于嵌套属性的动态访问,您需要进行迭代检查。但是,您也可以使用try catch并解析错误消息ugliness以访问undefined属性。如
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")}
我必须同意它非常难看。