我有一个存储false或true的变量,但我需要分别为0或1。我该怎么做呢?
当前回答
在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。
为那些有兴趣了解更多的人写了一篇博客。
其他回答
您可以通过简单地扩展布尔原型来做到这一点
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。
Javascript有一个三元操作符,你可以使用:
var i = result ? 1 : 0;
在我的上下文中,React Native,我从布尔获取不透明度值,最简单的方法:使用一元+运算符。
+ true; // 1
+ false; // 0
这将布尔值转换为数字;
style={ opacity: +!isFirstStep() }
let integerVariable = booleanVariable * 1;
我更喜欢用数字函数。它接受一个对象并将其转换为一个数字。
例子:
var myFalseBool = false;
var myTrueBool = true;
var myFalseInt = Number(myFalseBool);
console.log(myFalseInt === 0);
var myTrueInt = Number(myTrueBool);
console.log(myTrueInt === 1);
你可以在jsFiddle中测试它。