我遇到了以下代码:
const bool isIntersect = ...;
const bool isReversed = ...
if(!isIntersect != isReversed) {
//some stuff
}
这对我来说很奇怪。问题是可以用更清晰的方式编写:
所以它似乎不是!isIntersect || isIntersect
也不是!isIntersect && isIntersect
。
答案 0 :(得分:2)
让我们绘制一个真值表:
isIntersect isReversed outcome
false false true
false true false
true false false
true true true
我们可以看到,它只是一个等价:
isIntersect == isReversed
所以你可以将代码简化为
if (isIntersect == isReversed) {
// some stuff
}
答案 1 :(得分:1)
if(isIntersect == isReversed) {
应该是一样的。
要在没有(in)相等运算符的情况下表示它,您需要否定XOR,
if(!(isIntersect ^ isReversed)) {
但这不太清楚。
答案 2 :(得分:1)
以下是四种结果方案:
场景1
constructor() {
this.token = localStorage.getItem('id_token');
// this.decodedJwt = this.jwt && window.jwt_decode(this.jwt);
this.decodedJwt = this.jwtHelper.decodeToken(this.token);
this.jwtDate = this.jwtHelper.getTokenExpirationDate(this.token);
this.jwtExpired = this.jwtHelper.isTokenExpired(this.token);
}
场景2
const bool isIntersect = true;
const bool isReversed = true;
if(!isIntersect != isReversed) {
// DOES RUN => ((!true) != true) => (false != true) => true
}
场景3
const bool isIntersect = true;
const bool isReversed = false;
if(!isIntersect != isReversed) {
// DOES NOT RUN => ((!true) != false) => (false != false) => false
}
场景4
const bool isIntersect = false;
const bool isReversed = true;
if(!isIntersect != isReversed) {
// DOES NOT RUN => ((!false) != true) => (true != true) => false
}
这为我们提供了以下真值表:
const bool isIntersect = false;
const bool isReversed = false;
if(!isIntersect != isReversed) {
// DOES RUN => ((!false) != false) => (true != false) => true
}
因此上述isIntersect isReversed outcome
==================================
false false true
false true false
true false false
true true true
中的代码运行:
if-statement
和isIntersect
同时为isReversed
OR
true
和isIntersect
同时为isReversed
可以这样理解:
false
使用De Morgan定理简化
if((isIntersect && isReversed) || (!isIntersect && !isReversed)) { ... }
最简单的表格声明:
if((isIntersect && isReversed) || !(isIntersect || isReversed)) { ... }
// May be more difficult to understand it this way
答案 3 :(得分:1)
测试是测试isIntersected
和isReversed
是否都为真,或者两者都是假的,所以测试它的方式更详细(但可能更容易理解)
if ((isIntersected && isReversed) || (!isIntersected && !isReversed))