如何在dojo或JavaScript中检查多个未定义项

How to check for multiple undefined in dojo or JavaScript?

本文关键字:检查 未定义 JavaScript dojo      更新时间:2023-09-26

我的项目中有以下代码。正如你所看到的,我不得不检查所有对象和属性的未定义this.view&this.view.formView&this.view.formView.dapSections&this.view.formView.dapsection.scrollTop.

我正在寻找一种同时检查所有未定义项的方法。有什么方法可以在JavaScript或dojo中做到这一点吗?

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

您可能还想尝试lang.exists()https://dojotoolkit.org/reference-guide/1.10/dojo/_base/lang.html#dojo-基本郎存在

if (lang.exists('view.view.formView._dapSections.scrollTop', this) {
    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;
}
  • 第一个参数是一个字符串,表示要查找的对象的属性
  • 第二个参数是,如果每个属性不存在,是否要创建它(你通常不想这样做)
  • 第三个参数是要用作查找上下文的对象