为什么JavaScript中没有逻辑异或?


当前回答

JavaScript的祖先可以追溯到C语言,而C语言没有逻辑异或运算符。主要是因为它没什么用。位异或非常有用,但在我多年的编程生涯中,我从未需要过逻辑异或。

如果你有两个布尔变量,你可以用:

if (a != b)

你可以用两个任意变量!将它们强制转换为布尔值,然后使用相同的技巧:

if (!a != !b)

这是相当晦涩的,当然值得评论。实际上,你甚至可以在这里使用按位的XOR操作符,尽管这对我来说太聪明了:

if (!a ^ !b)

其他回答

试试这个简短易懂的

function xor(x,y){return true==(x!==y);}

function xnor(x,y){return !xor(x,y);}

这适用于任何数据类型

查看:

JavaScript中的逻辑异或

你可以这样模仿它:

if( ( foo && !bar ) || ( !foo && bar ) ) {
  ...
}

两个布尔值的异或仅仅是它们是否不同,因此:

Boolean(a) !== Boolean(b)

Cond1 xor cond2等价于Cond1 + cond2 == 1:

证明如下:

Let ops = [[false, false],[false, true], [true, false],[true, true]]; 函数xor(cond1, cond2){ 返回cond1 + cond2 == 1; } For (op of ops){ console.log(“$ {op [0]} xor $ {op [1]} $ {xor (op [0], op[1])}”) }

嘿,我找到了这个解决方案,在JavaScript和TypeScript上制作和XOR。

if( +!!a ^ +!!b )
{
  //This happens only when a is true and b is false or a is false and b is true.
}
else
{
  //This happens only when a is true and b is true or a is false and b is false
}