Javascript 中的 XOR 运算符以检查值

XOR operator in Javascript to check against value

因此,据我检查,javascript 没有 XOR 运算符。

有以下-

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

如果 foo 和 bar 是布尔值,这就很清楚了。但是异或可以用来检查不同类型的表达式吗?例如,如果我想根据另一个值检查一个值,即 -

if (type === 'configuration' XOR type2 === 'setup') { ... }

它会变成类似 -

的东西吗

if ( (type === 'configuration' && type2 !== 'setup') || (type !== 'configuration' && type2 === 'setup' ) ) { ... } 还是会看起来不一样?

这给出了以下结果 -

type = 'configuration' && type2 = 'setup': false type = 'configurations' && type2 = 'setup': true type = 'configuration' && type2 = 'setups': true type = 'configurations' && type2 = 'setups': false

匹配

0 XOR 0 = 0 0 XOR 1 = 1 1 XOR 0 = 1 1 XOR 1 = 0

但我不确定这是否适用于所有情况。

最简单的逻辑异或是:

a !== b

或者您的情况:

if((type === 'configuration') !== (type2 === 'setup'))

javascript 中还有一个按位异或 (^) 在这里也适用,因为布尔值被类型转换为 0 / 1,反之亦然:

if((type === "configuration") ^ (type2 === "setup"))