我需要测试是否恰好有三个布尔值中的两个为真。
类似于这样:
if ((a && b && !c) || (a && !b && c) || (!a && b && c)) {
// success
}
这是最直接的方法吗?有没有人知道快捷方式或速记?
我需要测试是否恰好有三个布尔值中的两个为真。
类似于这样:
if ((a && b && !c) || (a && !b && c) || (!a && b && c)) {
// success
}
这是最直接的方法吗?有没有人知道快捷方式或速记?
如果您将这些值相加,可以检查结果是否为2
if ((a + b + c) == 2) {
// do something
}
Number(a) + Number(b) + Number(c)
更容易让其他程序员看出你的意图。我完全支持程序员编写易于理解的代码。 - Keith(!a + !b + !c) ==1
更明显地测试它们中只有一个是假的? - traktor我会选择这种易读的方式:
let conditions = [a && b && !c, a && !b && c, !a && b && c]
if(conditions.filter(c => c).length === 2) { /* ... */}
你甚至不需要转换它们。
let a = true;
let b = true;
let c = false;
if(a + b + c === 2) {
console.log('You won!');
} else {
console.log('Not 2');
}
==
,而是 +
,它会将布尔值隐式转换为数字。(通常情况下,如果其中一个参数已经是字符串,则我认为 +
会将另一个参数转换为字符串,否则它会将它们都转换为数字。) - Robin Zigmond你可以将这些布尔值转换(强制转换)为整数并将它们相加。然后检查它是否等于2。像这样(C语言):
int res = (int)a + (int)b + (int)c;
if (res == 2) { /* Do something... */ }
编辑:
对于 JavaScript,你甚至不需要转换数值类型:
const res = a + b + c
if (res == 2) { /* Do something... */ }
function boolTest(a, b, c) {
if ((a && b && !c) || (a && !b && c) || (!a && b && c)) {
return true
} else {
return false
}
}
然后,您可以像这样使用它:
boolTest(true, true, false) // returns true
boolTest(false, true, false) // returns false
1
和0
),并且这些整数可以用作布尔值。请参见以下示例:
if (1) {
console.log("1 is true");
} else {
console.log("1 is false");
}
if (0) {
console.log("0 is true");
} else {
console.log("0 is false");
}
因此,要检查三个布尔值中的两个,您可以这样做:
var a = true;
var b = false;
var c = true;
var total = (a ? 1 : 0) + (b ? 1 : 0) + (c ? 1 : 0);
if (total == 2) {
console.log("Success!");
}
希望这能有所帮助!
a=true;
b=true;
c=false;
arr = [a,b,c]
result = arr.reduce((acc, cur) => acc+cur) == 2;
console.log(result);
这种方法的优点包括:
对于更长的数组,可以考虑一种性能更好的解决方案,该解决方案在达到所需数字后立即停止求和。
n=2
// large array
arr=[true,true,true].concat(Array(10000).fill(false))
// reduce will stop as soon as result is >n
result = arr.slice(0).reduce((acc, cur, i, a) => {acc+=cur; if (acc>n) a.splice(1); return acc});
console.log(result==2)