Convert boolean result into number/integer

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

    The unary + operator will take care of this:

    var test = true;
    // +test === 1
    test = false;
    // +test === 0
    

    You'll naturally want to sanity-check this on the server before storing it, so that might be a more sensible place to do this anyway, though.

提交回复
热议问题