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


当前回答

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

其他回答

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

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

!!a ^ !!b

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

Boolean(a) !== Boolean(b)

查看:

JavaScript中的逻辑异或

你可以这样模仿它:

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

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