Convert boolean result into number/integer

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

提交回复
热议问题