Why is there no logical xor in JavaScript?

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

Why is there no logical xor in JavaScript?

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

    One liner for Boolean:

    if (x ? !y : y) { do something cool }
    
    0 讨论(0)
  • 2020-11-29 17:23

    Convert values into Boolean form then take bitwise XOR. It will help with non-boolean values as well.

    Boolean(a) ^ Boolean(b)
    
    0 讨论(0)
  • 2020-11-29 17:23

    there is... sort of:

    if( foo ? !bar : bar ) {
      ...
    }
    

    or easier to read:

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

    why? dunno.

    because javascript developers thought it would be unnecessary as it can be expressed by other, already implemented, logical operators.

    you could as well just have gon with nand and thats it, you can impress every other possible logical operation from that.

    i personally think it has historical reasons that drive from c-based syntax languages, where to my knowledge xor is not present or at least exremely uncommon.

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

    In above xor function it will result SIMILAR result as logical xor does not exactly logical xor, means it will result "false for equal values" and "true for different values" with data type matching in consideration.

    This xor function will work as actual xor or logical operator, means it will result true or false according to the passing values are truthy or falsy. Use according to your needs

    function xor(x,y){return true==(!!x!==!!y);}
    
    function xnor(x,y){return !xor(x,y);}
    
    0 讨论(0)
  • 2020-11-29 17:24

    cond1 xor cond2 is equivalent to cond1 + cond 2 == 1:

    Here's the proof :

    let ops = [[false, false],[false, true], [true, false], [true, true]];
    
    function xor(cond1, cond2){
      return cond1 + cond2 == 1;
    }
    
    for(op of ops){
      console.log(`${op[0]} xor ${op[1]} is ${xor(op[0], op[1])}`)
    }

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

    Hey I found this solution, to make and XOR on JavaScript and TypeScript.

    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
    }
    
    0 讨论(0)
提交回复
热议问题