我有一个存储false或true的变量,但我需要分别为0或1。我该怎么做呢?
当前回答
当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章的类型转换。
其他回答
一元的+运算符会处理这些:
var test = true;
// +test === 1
test = false;
// +test === 0
您自然希望在存储它之前在服务器上检查它,因此在服务器上执行此操作可能是一个更明智的地方。
当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章的类型转换。
我更喜欢用数字函数。它接受一个对象并将其转换为一个数字。
例子:
var myFalseBool = false;
var myTrueBool = true;
var myFalseInt = Number(myFalseBool);
console.log(myFalseInt === 0);
var myTrueInt = Number(myTrueBool);
console.log(myTrueInt === 1);
你可以在jsFiddle中测试它。
+ ! !允许你对一个变量应用这个,即使它是未定义的:
+!!undefined // 0
+!!false // 0
+!!true // 1
+!!(<boolean expression>) // 1 if it evaluates to true, 0 otherwise
let integerVariable = booleanVariable * 1;