Javascript - "if (a && b || !a && !b)"有更清晰的表达方式吗?
Javascript - Is there a clearer way to express "if (a && b || !a && !b)"?
想表达"if both/neither a and/nor b are true",即a和b的布尔值相同
您可以使用 !(a ^ b)
或 !a === !b
:
test(true, true);
test(false, false);
test(true, false);
test(false, 1); // 1 = truthy value
test(false, ""); // "" = falsy value
function test(a, b) {
console.log(`!(${JSON.stringify(a)} ^ ${JSON.stringify(b)}) => ${!(a ^ b)}`);
console.log(`!${JSON.stringify(a)} === !${JSON.stringify(b)} => ${!a === !b}`);
}
.as-console-wrapper {
max-height: 100% !important;
}
^
是异或 (XOR) 运算符。它将其操作数转换为数字(true
=> 1
、false
=> 0
)并对它们进行异或。
!a === !b
有效,因为任何 !
将任何真值转换为 false
,将任何假值转换为 true
,然后您可以直接比较它们。
有很多方法,但由于人们不习惯比较布尔结果是否相等,而且在 JS 中养成这种习惯是一种危险的习惯,所以我喜欢:
if (a ? b : !b) {
...
}
想表达"if both/neither a and/nor b are true",即a和b的布尔值相同
您可以使用 !(a ^ b)
或 !a === !b
:
test(true, true);
test(false, false);
test(true, false);
test(false, 1); // 1 = truthy value
test(false, ""); // "" = falsy value
function test(a, b) {
console.log(`!(${JSON.stringify(a)} ^ ${JSON.stringify(b)}) => ${!(a ^ b)}`);
console.log(`!${JSON.stringify(a)} === !${JSON.stringify(b)} => ${!a === !b}`);
}
.as-console-wrapper {
max-height: 100% !important;
}
^
是异或 (XOR) 运算符。它将其操作数转换为数字(true
=> 1
、false
=> 0
)并对它们进行异或。
!a === !b
有效,因为任何 !
将任何真值转换为 false
,将任何假值转换为 true
,然后您可以直接比较它们。
有很多方法,但由于人们不习惯比较布尔结果是否相等,而且在 JS 中养成这种习惯是一种危险的习惯,所以我喜欢:
if (a ? b : !b) {
...
}