Javascript中的XOR运算符以检查值

时间:2018-07-04 08:14:02

标签: javascript logical-operators xor

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

有以下内容-

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

如果foo和bar是布尔值,则很明显。但是,可以使用XOR来检查不同类型的表达式吗?例如,如果我想对照另一个值检查一个值,即-

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

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

1 个答案:

答案 0 :(得分:1)

最简单的逻辑异或是:

a !== b

或者您的情况:

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

JavaScript中也有按位异或(^)在这里也可以使用,因为布尔类型转换为0/1,反之亦然:

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