检查三个布尔中是否有两个是正确的?

时间:2018-12-21 22:13:13

标签: javascript boolean

我需要测试三个布尔中是否有两个是正确的。

类似这样的东西:

if((a && b && !c) || (a && !b && c) || (!a && b && c)){
 //success
}

这是解决此问题的最直接方法吗?有人知道快捷方式/速记吗?

8 个答案:

答案 0 :(得分:3)

如果添加这些值,则可以检查结果是否为2

if ((a + b + c) == 2) {
    // do something
}

答案 1 :(得分:3)

要检查两个数字是否等于true

[a, b, c].filter(Boolean).length === 2;

参考文献:

答案 2 :(得分:1)

您甚至根本不需要转换它们。

let a = true;
let b = true;
let c = false;

if(a + b + c === 2) {
    console.log('You won!');
} else {
    console.log('Not 2');
}

答案 3 :(得分:0)

您只需将这些布尔值转换(转换)为整数并将它们加在一起即可。然后检查它是否等于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... */ }

答案 4 :(得分:0)

如果您试图查看三个布尔中是否有两个确实正确,那么可以使用一个函数来缩短代码。

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

答案 5 :(得分:0)

我会采用这种可读(IMO)的方式:

let conditions = [a && b && !c, a && !b && c, !a && b && c]
if(conditions.filter(c => c).length === 2) { /* ... */}

答案 6 :(得分:0)

在JavaScript(和大多数其他现代编码语言)中,布尔变量可以存储为二进制整数(10),而这些整数可以用作布尔值。参见以下示例:

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!");
}

希望这会有所帮助!

答案 7 :(得分:0)

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)