简体   繁体   English

如何比较 TypeScript 中的 2 个 boolean 值

[英]How to compare 2 boolean values in TypeScript

I'm trying to compare to boolean value in a if .我正在尝试与if中的 boolean 值进行比较。 I would like to do something like this:我想做这样的事情:

value1 = false;
value2 = true;

if (value1 === value2) {
  ... Some code ...
}

In JAVA you can use Boolean.compare(boolean a, boolean b) , but I can't find something equal in TypeScript. In JAVA you can use Boolean.compare(boolean a, boolean b) , but I can't find something equal in TypeScript.
For context, Boolean.compare(boolean a, boolean b) returns :对于上下文, Boolean.compare(boolean a, boolean b)返回

  • 0 if a is equal to b , 0 如果a等于b
  • a negative value if a is false and b is true,如果a为假且b为真,则为负值,
  • a positive value if a is true and b is false.如果a为真且b为假,则为正值。

Thanks for you help谢谢你的帮助

Edited: to show the message I get编辑:显示我收到的消息

在此处输入图像描述

This condition will always return 'false' since the types 'true' and 'false' have no overlap此条件将始终返回 'false',因为类型 'true' 和 'false' 没有重叠

Javascript doesn't have a builtin that's comparable to Java's Boolean.compare() . Javascript 没有可与 Java 的Boolean.compare()相媲美的内置函数。 In fact, the Boolean class has nearly nothing in it, outside the constructor, toString() and valueOf() .实际上,除了构造函数toString()valueOf()之外, Boolean class几乎没有任何内容。

If you want to replicate the functionality yourself, you can use the Number constructor .如果您想自己复制功能,可以使用Number构造函数

function booleanCompare(a: boolean, b: boolean) {
    return Number(a) - Number(b);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM