返回true如果两个布尔是真实的,但也可以为空或不存在

问题描述 投票:0回答:1

我有一个关于回归true的明确的方式问题,如果两个布尔是true但也可以是空的。我的意思是可以有一个,甚至非布尔值,有应该也是如此。到目前为止,我使用:

var isSelectedM = true;
var isSelectedE = true;
if(this.getModel("info").getProperty("/dep")) {
    isSelectedM = this.byId("checkBoxM").getSelected();
}
if(this.getModel("info").getProperty("/sta")) {
    isSelectedE = this.byId("checkBoxE").getSelected();
}
return (isSelectedM && isSelectedE);

我在这里看到了两个问题 - 我想开始与这两个值作为false,然后可能会改变他们true和第二要花那么多行。我怎样才能做到这一点更清楚,因为我不喜欢现在我的代码?

javascript refactoring sapui5
1个回答
2
投票

我使用数组,含有getProperty字符串及其链接byId串的子阵列的阵列,并使用every测试:

const items = [
  ['/dep', 'checkBoxM'],
  ['/sta', 'checkBoxE']
]
return items.every(([prop, id]) => (
  !this.getModel("info").getProperty(prop)
  || this.byId(id).getSelected()
);

这样做的另一个好处是,它很容易扩展到3个或更多的项目非常少的代码,只需添加到items阵列。

或者,在丑陋的ES5:

var items = [
  ['/dep', 'checkBoxM'],
  ['/sta', 'checkBoxE']
];
for (var i = 0; i < items.length; i++) {
  var item = items[i];
  if (this.getModel("info").getProperty(item[0])
  && !this.byId(item[1]).getSelected()) {
    return false;
  }
}
return true;

正如你所看到的,该代码是很多更详细的,更难以了解 - 我推荐使用巴贝尔和polyfills代替。

© www.soinside.com 2019 - 2024. All rights reserved.