Why is there no logical xor in JavaScript?

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

Why is there no logical xor in JavaScript?

相关标签:
19条回答
  • 2020-11-29 17:25

    Check out:

    • Logical XOR in JavaScript

    You can mimic it something like this:

    if( ( foo && !bar ) || ( !foo && bar ) ) {
      ...
    }
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-29 17:26

    The reason there is no logical XOR (^^) is because unlike && and || it does not give any lazy-logic advantage. That is the state of both expressions on the right and left have to be evaluated.

    0 讨论(0)
  • 2020-11-29 17:27

    Yes, Just do the following. Assuming that you are dealing with booleans A and B, then A XOR B value can be calculated in JavaScript using the following

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

    The previous line is also equivalent to the following

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

    Personally, I prefer xor1 since I have to type less characters. I believe that xor1 is also faster too. It's just performing two calculations. xor2 is performing three calculations.

    Visual Explanation ... Read the table bellow (where 0 stands for false and 1 stands for true) and compare the 3rd and 5th columns.

    !(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     |
    ------------------------------------------
    

    Enjoy.

    0 讨论(0)
  • 2020-11-29 17:38

    The XOR of two booleans is simply whether they are different, therefore:

    Boolean(a) !== Boolean(b)
    
    0 讨论(0)
  • 2020-11-29 17:39

    In Typescript (The + changes to numeric value):

    value : number = (+false ^ +true)
    

    So:

    value : boolean = (+false ^ +true) == 1
    
    0 讨论(0)
提交回复
热议问题