Convert boolean result into number/integer

前端 未结 18 2074
刺人心
刺人心 2020-12-02 05:21

I have a variable that stores false or true, but I need 0 or 1 instead, respectively. How can I do this?

相关标签:
18条回答
  • 2020-12-02 06:14

    Imho the best solution is:

    fooBar | 0
    

    This is used in asm.js to force integer type.

    0 讨论(0)
  • 2020-12-02 06:14
    let integerVariable = booleanVariable * 1;
    
    0 讨论(0)
  • 2020-12-02 06:15

    Javascript has a ternary operator you could use:

    var i = result ? 1 : 0;
    
    0 讨论(0)
  • 2020-12-02 06:15

    I prefer to use the Number function. It takes an object and converts it to a number.

    Example:

    var myFalseBool = false;
    var myTrueBool = true;
    
    var myFalseInt = Number(myFalseBool);
    console.log(myFalseInt === 0);
    
    var myTrueInt = Number(myTrueBool);
    console.log(myTrueInt === 1);
    

    You can test it in a jsFiddle.

    0 讨论(0)
  • 2020-12-02 06:17

    I just came across this shortcut today.

    ~~(true)

    ~~(false)

    People much smarter than I can explain:

    http://james.padolsey.com/javascript/double-bitwise-not/

    0 讨论(0)
  • 2020-12-02 06:18

    When JavaScript is expecting a number value but receives a boolean instead it converts that boolean into a number: true and false convert into 1 and 0 respectively. So you can take advantage of this;

    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 or shortened to +t === 1
    console.log(+f); //0+f === 0 or shortened to +f === 0

    Further reading Type Conversions Chapter 3.8 of The Definitive Guide to Javascript.

    0 讨论(0)
提交回复
热议问题