Why is there no logical xor in JavaScript?

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

Why is there no logical xor in JavaScript?

19条回答
  •  無奈伤痛
    2020-11-29 17:42

    Here's an alternate solution that works with 2+ variables and provides count as bonus.

    Here's a more general solution to simulate logical XOR for any truthy/falsey values, just as if you'd have the operator in standard IF statements:

    const v1 = true;
    const v2 = -1; // truthy (warning, as always)
    const v3 = ""; // falsy
    const v4 = 783; // truthy
    const v5 = false;
    
    if( ( !!v1 + !!v2 + !!v3 + !!v4 + !!v5 ) === 1 )
      document.write( `[ ${v1} XOR ${v2} XOR "${v3}" XOR ${v4} XOR ${v5} ] is TRUE!` );
    else
      document.write( `[ ${v1} XOR ${v2} XOR "${v3}" XOR ${v4} XOR ${v5} ] is FALSE!` );

    The reason I like this, is because it also answers "How many of these variables are truthy?", so I usually pre-store that result.

    And for those who want strict boolean-TRUE xor check behaviour, just do:

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

    If you don't care about the count, or if you care about optimal performance: then just use the bitwise xor on values coerced to boolean, for the truthy/falsy solution:

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

提交回复
热议问题