为什么JavaScript中没有逻辑异或?
当前回答
嘿,我找到了这个解决方案,在JavaScript和TypeScript上制作和XOR。
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
}
其他回答
查看:
JavaScript中的逻辑异或
你可以这样模仿它:
if( ( foo && !bar ) || ( !foo && bar ) ) {
...
}
Javascript有一个按位的异或运算符:^
var nb = 5^9 // = 12
你可以将它与布尔值一起使用,它会将结果作为0或1(你可以将其转换回布尔值,例如result = !!(op1 ^ op2)。但正如John所说,它等价于result = (op1 != op2),这更清楚。
如何将结果int转换为带有双重否定的bool ?不是很漂亮,但是很紧凑。
Var state1 = false, State2 = true; var A = state1 ^ state2;//将变成1 var B = !!(state1 ^ state2);//将变为true console.log(一个); console.log (B);
Boolean的一行代码:
if (x ? !y : y) { do something cool }
转换为布尔值,然后执行异或,比如-
!!a ^ !!b