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


当前回答

如何将结果int转换为带有双重否定的bool ?不是很漂亮,但是很紧凑。

Var state1 = false, State2 = true; var A = state1 ^ state2;//将变成1 var B = !!(state1 ^ state2);//将变为true console.log(一个); console.log (B);

其他回答

为了子孙后代的利益,也因为我发现这是一个很好的练习,您可以很容易地利用XOR操作符来强制使用真实性。就像被选中的答案一样,它可能有点太聪明了。

const xor = (a, b) => !!(!!a ^ !!b)

console.log(undefined ^ {}) // Returns 0, bitwise can't be done here.
console.log(xor(undefined, {})) // Returns true, because {} is truthy and undefined is falsy
console.log(0 ^ 1) // Works naturally, returns 1
console.log(xor(0, 1)) // Also works, returns true
console.log(true ^ false) // Again, returns true
console.log(xor(true, false)) // And again, returns true...

为了好玩,这应该在TypeScript中工作,通过强制显式的any:

const xor = (a: any, b: any) => !!((!!a as any) ^ (!!b as any))

有……类:

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

或者更容易读:

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

为什么?不晓得。

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

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

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

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函数将作为实际的xor或逻辑运算符工作,这意味着它将根据传递的值是真还是假而得到真或假的结果。根据您的需要使用

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

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

Javascript有一个按位的异或运算符:^

var nb = 5^9 // = 12

你可以将它与布尔值一起使用,它会将结果作为0或1(你可以将其转换回布尔值,例如result = !!(op1 ^ op2)。但正如John所说,它等价于result = (op1 != op2),这更清楚。