I saw this piece of code in the underscore.js source:
if ((!a && b) || (a && !b)) r开发者_Go百科eturn false;
Is that equivalent to the following?
if (a ^ b) return false;
Strictly speaking, no. &&
and ||
are logical operators, whereas ^
is a bit-wise operator.
But if your inputs are booleans (or integers from the set {0, 1}), then the semantics will be basically the same. If you can't guarantee these inputs, you can still ensure identical semantics thus:
if (!a ^ !b) return false;
(Assuming, of course, that a
and b
are plain variables, not complex expressions with side-effects.)
Those two are not the same because a ^ b
is a bitwise xor function instead of a logical xor function. So, if a = 1
and b = 2
, then a ^ b=3
but you would want a falsy value because both a
and b
are truthy.
精彩评论