在 Javascript 中转换 True->1 和 False->0?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14787761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:55:10  来源:igfitidea点击:

Convert True->1 and False->0 in Javascript?

javascript

提问by Royi Namir

Besides :

除了 :

true ? 1 : 0

true ? 1 : 0

is there any short trick which can "translate" True->1and False->0in Javascript ?

是否有任何可以“翻译”True->1False->0在 Javascript 中的简短技巧?

I've searched but couldn't find any alternative

我已经搜索过但找不到任何替代方案

Whatdo you mean by "short trick" ?

你说的“小技巧”是什么意思?

answer : same as ~~6.6is a trick forMath.floor

回答 : 同样~~6.6是一个技巧Math.floor

回答by Paul S.

Lots of ways to do this

有很多方法可以做到这一点

// implicit cast
+true; // 1
+false; // 0
// bit shift by zero
true >>> 0; // 1, right zerofill
false >>> 0; // 0
true << 0; // 1, left
false << 0; // 0
// double bitwise NOT
~~true; // 1
~~false; // 0
// bitwise OR ZERO
true | 0; // 1
false | 0; // 0
// bitwise AND ONE
true & 1; // 1
false & 1; // 0
// bitwise XOR ZERO, you can negate with XOR ONE
true ^ 0; // 1
false ^ 0; // 0
// even PLUS ZERO
true + 0; // 1
false + 0; // 0
// and MULTIPLICATION by ONE
true * 1; // 1
false * 1; // 0

You can also use division by 1, true / 1; // 1, but I'd advise avoiding division where possible.

您也可以使用除法1, true / 1; // 1,但我建议尽可能避免除法。

Furthermore, many of the non-unary operators have an assignment versionso if you have a variable you want converted, you can do it very quickly.

此外,许多非一元运算符都有赋值版本,因此如果您有要转换的变量,则可以非常快速地完成。

You can see a comparison of the different methods with this jsperf.

您可以通过此 jsperf看到不同方法的比较。

回答by bsiamionau

...or you can use +trueand +false

...或者你可以使用+true+false

回答by whirlwin

You can use ~~boolean, where booleanis (obviously) a boolean.

您可以使用~~boolean, whereboolean是(显然)一个布尔值。

~~true  // 1
~~false // 0

回答by Muhammad

Another way could be using Number()

另一种方法可能是使用 Number()

Number(true) = 1
Number(false) = 0