我有一个存储false或true的变量,但我需要分别为0或1。我该怎么做呢?
当前回答
您可以通过简单地扩展布尔原型来做到这一点
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。
其他回答
let integerVariable = booleanVariable * 1;
使用一元+运算符,将其操作数转换为数字。
+ true; // 1
+ false; // 0
当然,请注意,您仍然应该在服务器端清除数据,因为用户可以将任何数据发送到您的服务器,而不管客户端代码说了什么。
try
val*1
让t = true; 让f = false; console.log (t * 1); console.log (f * 1)
在我的上下文中,React Native,我从布尔获取不透明度值,最简单的方法:使用一元+运算符。
+ true; // 1
+ false; // 0
这将布尔值转换为数字;
style={ opacity: +!isFirstStep() }
我今天偶然发现了这条近路。
~ ~(真正的)
~ ~(假)
比我聪明得多的人可以解释:
http://james.padolsey.com/javascript/double-bitwise-not/