Why is there no logical xor in JavaScript?

前端 未结 19 2113
忘了有多久
忘了有多久 2020-11-29 17:17

Why is there no logical xor in JavaScript?

19条回答
  •  Happy的楠姐
    2020-11-29 17:26

    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.

    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)
    

    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)
    

提交回复
热议问题