如何在 dojo 或 JavaScript 中检查多个 undefined?

How to check for multiple undefined in dojo or JavaScript?

我的项目中有以下代码。如您所见,我必须检查所有对象和属性的未定义 this.view && this.view.formView && this.view.formView._dapSections && this.view.formView._dapSections.scrollTop

我正在寻找一种方法来检查 once.Is 中所有未定义的内容,在 JavaScript 或 dojo 中有什么方法可以做到这一点?

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

这正是 dojo/_base/lang.getObject 设计的目的。

var scrollTop = lang.getObject('view.formView._dapSections.scrollTop', false, this);
if (scrollTop) {
    globals.lastScrollPosition = scrollTop;
}
  • 第一个参数是一个字符串,表示要查找的对象的属性
  • 第二个参数是是否创建每个 属性 如果它不存在(你通常不想这样做)
  • 第三个参数是用作查找上下文的对象

您可能还想试试 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;
}