【发布时间】:2018-12-12 14:40:50
【问题描述】:
所以,据我检查,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
但我不确定这是否适用于所有情况。
【问题讨论】:
-
你可以定义
const xor = (a, b) => a && !b || !a && b,然后直接使用xor(type === 'configuration', type2 === 'setup')。这是简单、可重用、可维护且易于阅读的。与位运算符和长逻辑表达式不同。
标签: javascript logical-operators xor