英文:
Javascript - Is there a clearer way to express "if (a && b || !a && !b)"?
问题
"如果a和b都为真,或者都不为真"
英文:
Would like to express "if both/neither a and/nor b are true", i.e. the boolean values of a and b are the same
答案1
得分: 1
你可以使用 !(a ^ b)
或 !a === !b
:
test(true, true);
test(false, false);
test(true, false);
test(false, 1); // 1 = 真值
test(false, ""); // "" = 假值
function test(a, b) {
console.log(`!(${JSON.stringify(a)} ^ ${JSON.stringify(b)}) => ${!(a ^ b)}`);
console.log(`!${JSON.stringify(a)} === !${JSON.stringify(b)} => ${!a === !b}`);
}
^
是异或(XOR)运算符。它将其操作数转换为数字(true
=> 1
,false
=> 0
)并对它们执行异或操作。
!a === !b
之所以有效,是因为任何 !
都会将任何真值转换为 false
,将任何假值转换为 true
,然后可以直接比较它们。
英文:
You can use !(a ^ b)
or !a === !b
:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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}`);
}
<!-- language: lang-css -->
.as-console-wrapper {
max-height: 100% !important;
}
<!-- end snippet -->
^
is the exclusive-or (XOR) operator. It converts its operands to numbers (true
=> 1
, false
=> 0
) and does an XOR on them.
!a === !b
works because any !
converts any truthy value to false
and any falsy value to true
, and then you can directly compare them.
答案2
得分: 0
Sure, here is the translation:
有很多方法,但由于人们不习惯比较布尔值的相等性,而且因为这在 JavaScript 中是一种危险的习惯,我喜欢:
if (a ? b : !b) {
...
}
英文:
There are lots of ways, but since people aren't used to comparing Boolean results for equality, and because it's a dangerous habit to get into in JS, I like:
if (a ? b : !b) {
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论