Convert boolean result into number/integer

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

    I created a JSperf comparison of all suggested answers.

    TL;DR - the best option for all current browsers is:

    val | 0;
    

    .

    Update:

    It seems like these days they are all pretty identical, except that the Number() function is the slowest, while the best being val === true ? 1 : 0;.

提交回复
热议问题