JavaScript – 是否有更清晰的方式来表达 “if (a && b || !a && !b)”?

huangapple go评论137阅读模式
英文:

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 => 1false => 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, &quot;&quot;); // &quot;&quot; = falsy value

function test(a, b) {
  console.log(`!(${JSON.stringify(a)} ^ ${JSON.stringify(b)}) =&gt; ${!(a ^ b)}`);
  console.log(`!${JSON.stringify(a)} === !${JSON.stringify(b)} =&gt; ${!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) {
    ...
}

huangapple
  • 本文由 发表于 2020年1月7日 00:34:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615726.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定