为什么JavaScript中没有逻辑xor? [英] Why is there no logical xor in JavaScript?
问题描述
为什么JavaScript中没有逻辑xor?
Why is there no logical xor in JavaScript?
推荐答案
JavaScript将其祖先追溯到C,C没有逻辑XOR运算符。主要是因为它没用。 Bitwise XOR非常有用,但在我多年的编程中,我从未需要逻辑XOR。
JavaScript traces its ancestry back to C, and C does not have a logical XOR operator. Mainly because it's not useful. Bitwise XOR is extremely useful, but in all my years of programming I have never needed a logical XOR.
如果你有两个布尔变量,你可以模仿XOR:
If you have two boolean variables you can mimic XOR with:
if (a != b)
使用两个任意变量,您可以使用!
将它们强制转换为布尔值,然后使用相同的技巧:
With two arbitrary variables you could use !
to coerce them to boolean values and then use the same trick:
if (!a != !b)
虽然这很晦涩,但肯定值得评论。实际上,你甚至可以在这一点上使用按位XOR运算符,虽然这对我来说太聪明了:
That's pretty obscure though and would certainly deserve a comment. Indeed, you could even use the bitwise XOR operator at this point, though this would be far too clever for my taste:
if (!a ^ !b)
这篇关于为什么JavaScript中没有逻辑xor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!