在Javascript中转换True-> 1和False-> 0? [英] Convert True->1 and False->0 in Javascript?

查看:105
本文介绍了在Javascript中转换True-> 1和False-> 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此外:

是真的吗? 1:0

是否有任何可以翻译的短技巧 True-> 1 False-> 0

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

我搜索过但找不到任何内容替代

I've searched but couldn't find any alternative

什么你的意思是短道理?

What do you mean by "short trick" ?

回答:与 ~~ 6.6 相同是 Math.floor

推荐答案

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

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

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

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

此外,许多非一元运算符都有 作业版 如果您有你想要转换的变量,你可以很快地完成。

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

你可以看到不同方法与 这个jsperf

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

这篇关于在Javascript中转换True-&gt; 1和False-&gt; 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆