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



我有一个关于明确的返回方式的问题,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。

最新更新