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


当前回答

试试这个简短易懂的

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

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

这适用于任何数据类型

其他回答

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])}”) }

将值转换为布尔形式,然后按位XOR:

Boolean(a) ^ Boolean(b) // === 0 | 1

注意,这个表达式的结果是一个数字,而不是一个布尔值。

位XOR也适用于非布尔值,但请记住,这是位操作符,而不是逻辑操作符。使用非bool可能不会像你预想的那样:

(5 ^ 3) === 6 // true

查看:

JavaScript中的逻辑异或

你可以这样模仿它:

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

有……类:

if( foo ? !bar : bar ) {
  ...
}

或者更容易读:

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

为什么?不晓得。

因为javascript开发人员认为这是不必要的,因为它可以用其他已经实现的逻辑运算符来表示。

你也可以只用nand,就是这样,你可以从它得到所有其他可能的逻辑运算。

我个人认为它有历史原因,从基于c的语法语言驱动,据我所知,xor不存在或至少非常罕见。

嘿,我找到了这个解决方案,在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
}