Is there anyway to implement XOR in javascript

前端 未结 18 692
孤城傲影
孤城傲影 2020-12-24 10:53

I\'m trying to implement XOR in javascript in the following way:

   // XOR validation
   if ((isEmptyString(firstStr) && !isEmptyString(secondStr)) |         


        
18条回答
  •  爱一瞬间的悲伤
    2020-12-24 11:47

    I pretend that you are looking for a logical XOR, as javascript already has a bitwise one (^) :)

    I usually use a simple ternary operator (one of the rare times I use one):

    if ((isEmptyString(firstStr) ? !isEmptyString(secondStr) 
                                 : isEmptyString(secondStr))) {
    alert(SOME_VALIDATION_MSG);
        return;
    }
    

    Edit:

    working on the @Jeff Meatball Yang solution

    if ((!isEmptyString(firstStr) ^ !isEmptyString(secondStr))) {
      alert(SOME_VALIDATION_MSG);
      return;
    }
    

    you negate the values in order to transform them in booleans and then apply the bitwise xor operator. Maybe it is not so maintainable as the first solution (or maybe I'm too accustomed to the first one)

提交回复
热议问题