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


当前回答

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中的逻辑异或

你可以这样模仿它:

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

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

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

这里有一个替代解决方案,与2+变量的工作,并提供计数作为奖金。

这里有一个更通用的解决方案来模拟任何真/假值的逻辑XOR,就像你在标准if语句中有运算符一样:

Const v1 = true; Const v2 = -1;// true(警告,一如既往) Const v3 = "";/ / falsy Const v4 = 783;/ /真相 Const v5 = false; 如果(!!)V1 + !!V2 + !!V3 + !!V4 + !!V5) === 1) 文档。写(“[$ {v1} XOR $ {v2} XOR " $ {v3} " XOR $ {v4} XOR $ {v5}]是真的!”); 其他的 文档。写(“[$ {v1} XOR $ {v2} XOR " $ {v3} " XOR $ {v4} XOR $ {v5}]是假的!”);

我喜欢这个的原因是,它还回答了“这些变量中有多少是真实的?”,所以我通常会预先存储这个结果。

对于那些想要严格的布尔- true异或检查行为的人,只需执行:

if( ( ( v1===true ) + ( v2===true ) + ( v3===true ) + ( v4===true ) + ( v5===true ) ) === 1 )
  // etc.

如果你不关心计数,或者如果你关心最优性能:那么只需对强制为布尔值的值按位使用xor,用于真/假解决方案:

if( !!v1 ^ !!v2 ^ !!v3 ^ !!v4 ^ !!v5 )
  // etc.