Return 如果两个布尔值都为真但也可以为空或不存在则为真

Return true if two booleans are true but also can be empty or not exists

我有一个关于 return 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,其次它需要很多行。我现在不喜欢我的代码,如何才能更清楚?

我会使用一个数组数组,包含 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;

如您所见,代码更冗长且更难理解 - 我建议改用 Babel 和 polyfills。