检查在Javascript中嵌套的对象的字段definedness
问题描述:
带宾语这样检查在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") ...
...还是有更好的方法吗?
答
通常为了动态访问嵌套属性,您需要进行迭代检查。但是,您也可以使用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")}
我不得不承认,这是很丑陋的。
你说预计会进行迭代检查:事实上,这是我的第一个想法。我认为这将是一个残酷的解决方案,但如果这是你所暗示的规范,我会为此而努力。我认为这种迭代检查可能有一个内置函数,我不知何故失踪... – resle