我有一个存储false或true的变量,但我需要分别为0或1。我该怎么做呢?


当前回答

我更喜欢用数字函数。它接受一个对象并将其转换为一个数字。

例子:

var myFalseBool = false;
var myTrueBool = true;

var myFalseInt = Number(myFalseBool);
console.log(myFalseInt === 0);

var myTrueInt = Number(myTrueBool);
console.log(myTrueInt === 1);

你可以在jsFiddle中测试它。

其他回答

依我看,最好的解决办法是:

fooBar | 0

这在asm.js中用于强制整型。

+ ! !允许你对一个变量应用这个,即使它是未定义的:

+!!undefined    // 0
+!!false        // 0
+!!true         // 1

+!!(<boolean expression>)  // 1 if it evaluates to true, 0 otherwise

Javascript有一个三元操作符,你可以使用:

var i = result ? 1 : 0;

将建议的方法放在jsben.ch中: https://jsben.ch/d33N1。

每个测试都会给出不同的结果,但是每个测试中最好的方法是位操作:0|bool / bool|0 / 1&bool / 1&bool / ~~bool。

try

val*1

让t = true; 让f = false; console.log (t * 1); console.log (f * 1)