我有一个存储false或true的变量,但我需要分别为0或1。我该怎么做呢?
当前回答
使用一元+运算符,将其操作数转换为数字。
+ true; // 1
+ false; // 0
当然,请注意,您仍然应该在服务器端清除数据,因为用户可以将任何数据发送到您的服务器,而不管客户端代码说了什么。
其他回答
将建议的方法放在jsben.ch中: https://jsben.ch/d33N1。
每个测试都会给出不同的结果,但是每个测试中最好的方法是位操作:0|bool / bool|0 / 1&bool / 1&bool / ~~bool。
+ ! !允许你对一个变量应用这个,即使它是未定义的:
+!!undefined // 0
+!!false // 0
+!!true // 1
+!!(<boolean expression>) // 1 if it evaluates to true, 0 otherwise
在JavaScript中,布尔到整数的转换可以通过以下方式完成:
使用数量() 使用三元 使用一元操作符 使用算术运算符 使用位操作符 使用位移位操作符
在之前的回答中,其中一些已经被涵盖,但是,你可以发现一些缺失的内容如下:
// using arithmetic operators
true + 0; // 1
false + 0; // 0
true - 0; // 1
false - 0; // 0
true * 1 // 1
false * 1 // 0
true / 1; // 1
false / 1; // 0
// using bitwise operators
true & 1; // 1
false & 1; // 0
true | 0; // 1
false | 0; // 0
true ^ 0; // 1
false ^ 0; // 0
// using bitwise shift operators
true >> 0; // 1
false >> 0; // 0
true >>> 0; // 1
false >>> 0; // 0
true << 0; // 1
false << 0; // 0
这些工作是因为JavaScript在执行这些操作时在内部将布尔值强制转换为整数等价物。
需要注意的一点是,当您不确定变量是否总是具有布尔值时,所有这些方法(除了使用三元操作符)都可能返回NaN。
为那些有兴趣了解更多的人写了一篇博客。
当JavaScript期望一个数字值但接收到一个布尔值时,它会将该布尔值转换为一个数字:true和false分别转换为1和0。所以你可以利用这个;
Var t = true; Var f = false; console.log (t * 1);// t*1 == 1 console.log (f * 1);// f*1 === 0 console.log (+ t);// 0+t === 1或缩短为+t === 1 console.log (+ f);//0+f === 0或缩短为+f === 0
进一步阅读Javascript权威指南第3.8章的类型转换。
您可以通过简单地扩展布尔原型来做到这一点
Boolean.prototype.intval = function(){return ~~this}
不太容易理解那里发生了什么所以另一个版本会是
Boolean.prototype.intval = function(){return (this == true)?1:0}
你可以做一些事情
document.write(true.intval());
当我使用布尔值存储条件时,我经常将它们转换为位域,在这种情况下,我最终使用了原型函数的扩展版本
Boolean.prototype.intval = function(places)
{
places = ('undefined' == typeof(places))?0:places;
return (~~this) << places
}
你可以这样做
document.write(true.intval(2))
它的输出是4。