Pat*_*iss 3 javascript xor logical-operators
所以,据我检查,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
但我不确定这是否适合所有情况。
最简单的逻辑异或是:
a !== b
Run Code Online (Sandbox Code Playgroud)
或者在你的情况下:
if((type === 'configuration') !== (type2 === 'setup'))
Run Code Online (Sandbox Code Playgroud)
javascript 中的按位异或 ( ^) 也适用于此,因为布尔值被类型转换为 0 / 1,反之亦然:
if((type === "configuration") ^ (type2 === "setup"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5387 次 |
| 最近记录: |