Convert boolean result into number/integer

前端 未结 18 2088
刺人心
刺人心 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: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.

提交回复
热议问题