How to check for multiple undefined in dojo or JavaScript?

岁酱吖の 提交于 2019-12-24 13:52:55

问题


I have the below piece of code in my project. As you can see, I had to check the undefined for all the object and properties this.view && this.view.formView && this.view.formView._dapSections && this.view.formView._dapSections.scrollTop.

I'm looking for a way to check undefined for all at once.Is there any way to do that in JavaScript or dojo?

if(this.view && this.view.formView && this.view.formView._dapSections && this.view.formView._dapSections.scrollTop) {
                globals.lastScrollPosition = this.view.formView._dapSections.scrollTop;
            }

回答1:


You might also want to try lang.exists() https://dojotoolkit.org/reference-guide/1.10/dojo/_base/lang.html#dojo-base-lang-exists

if (lang.exists('view.view.formView._dapSections.scrollTop', this) {
    globals.lastScrollPosition = this.view.formView._dapSections.scrollTop;
}



回答2:


This is precisely the sort of thing that dojo/_base/lang.getObject is designed for.

var scrollTop = lang.getObject('view.formView._dapSections.scrollTop', false, this);
if (scrollTop) {
    globals.lastScrollPosition = scrollTop;
}
  • The first argument is a string representing the properties on the object to look up
  • The second argument is whether to create each property if it doesn't exist (you usually don't want to do that)
  • The third argument is the object to use as the context for the lookup


来源:https://stackoverflow.com/questions/33741024/how-to-check-for-multiple-undefined-in-dojo-or-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!