如何解决仅在设置了相应标志时评估条件的一部分
例如,我将flag1
,flag2
,flag3
,...,flagN
作为标志的布尔值。
我需要编写如下if语句:如果flagK
是false
,则关闭条件的“ K”部分:
if (condition0 && (flag1 && condition1) && (flag2 && condition2) ... && (flagN && conditionN))
{
// do something
}
// For example,if flag 2 is false then the condition should only be:
if (condition0 && (flag1 && condition1) && ... && (flagN && conditionN))
{
//do something}
}
特别地,给出一个这样的例子(仅用于演示,不是我的真正问题):
const divby2 = false; //if this is false,then ignore the **i%2 === 0** below
const divby3 = true;
const divby4 = true;
const divby5 = true;
//......const divbyN....
const array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,42,45,241,526]
array.forEach((i) => {
if(i >= 0 && (divby2 && i%2 === 0) && (divby3 && i%3 === 0)) {
console.log(i) // output here should be 3,12 instead of nothing
}
}
)
解决方法
我将根据您的条件创建一个对象,然后过滤掉您不想运行的功能,然后将对象简化为一个可运行所有已启用功能的功能:
const conditions = {
divby2: i => i % 2 === 0,divby3: i => i % 3 === 0,};
const enabled = {
divby2: false,//if this is false,then need to ignore the **i%2 === 0** below
divby3: true
}
const enabledConditions = (i) => {
return Object.entries(conditions).filter(
([key,value]) => enabled[key]
).reduce((carry,[_,condition]) => {
return condition(i) && carry
},i !== false);
}
//......const divbyN....
const array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,42,45,241,526]
array.forEach((i) => {
if(i >= 0 && enabledConditions(i)){
console.log(i) //output here should be 3,12 instead of nothing
}
}
)
,
您要查找的术语是“短路”,类似于实际电子电路中的方式,如果某些部分不起作用,则只需将其短路并顺畅流动即可。
if(i >= 0 && ( divby2 && i%2 === 0 || !divby2) && (divby3 && i%3 === 0))
在这种情况下,如果您希望在设置divby2
= true
时将过滤后的数字除以2即可
当您只想忽略和不关心2的除数时,可以设置divby2
= false
以伪造
(is-checking-for-divby-2? AND is-current-number-divby-2?) OR (NOT is-checking-for-divby-2?)
不检查divby 2时,请将该逻辑片段设为true,这样就不会影响对以下逻辑片段的评估
然后..你为什么要麻烦将此片段设为TRUE?
因为您AND
将它们
类似地,您可以申请divby3
,divby4
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。