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


当前回答

为了子孙后代的利益,也因为我发现这是一个很好的练习,您可以很容易地利用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))

其他回答

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

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

if (a != b)

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

if (!a != !b)

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

if (!a ^ !b)

转换为布尔值,然后执行异或,比如-

!!a ^ !!b

是的,按照下面的步骤做。 假设您正在处理布尔值A和B,那么可以使用以下代码在JavaScript中计算XOR B值

var xor1 = !(a === b);

上一行也相当于下面一行

var xor2 = (!a !== !b);

就我个人而言,我更喜欢xor1,因为我需要输入更少的字符。我相信xor1也更快。它只是进行了两次计算。Xor2执行三次计算。

视觉讲解…阅读下面的表格(0代表假,1代表真),比较第3列和第5列。

(a === b):

| A | B | A XOR B | A === B | !(A === B) |
------------------------------------------
| 0 | 0 |    0    |    1    |      0     |
| 0 | 1 |    1    |    0    |      1     |
| 1 | 0 |    1    |    0    |      1     |
| 1 | 1 |    0    |    1    |      0     |
------------------------------------------

享受。

没有逻辑异或(^^)的原因是,与&&和||不同,它没有提供任何惰性逻辑优势。也就是左右两边表达式的状态都要求值。

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