gpt4 book ai didi

javascript - 如果两个 bool 值都为 true,则返回 true,但也可以为空或不存在

转载 作者:行者123 更新时间:2023-12-01 01:18:13 25 4
gpt4 key购买 nike

如果两个 bool 值都为 true 但也可以为空,我有一个关于返回 true 的明确方式的问题。我的意思是,可以有一个 bool 值,甚至可以有一个非 bool 值,而且它也应该是真的。到目前为止我使用:

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()
);

这样做的另一个好处是,只需很少的额外代码,只需添加到 items 数组即可轻松扩展到 3 个或更多项目。

或者,在丑陋的 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。

关于javascript - 如果两个 bool 值都为 true,则返回 true,但也可以为空或不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54512015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com