Convert True->1 and False->0 in Javascript?

后端 未结 5 841
旧时难觅i
旧时难觅i 2020-12-22 23:22

Besides :

true ? 1 : 0

is there any short trick which can \"translate\" True->1 and False->0 in Javascript ?

相关标签:
5条回答
  • 2020-12-23 00:03

    Another way could be using Number()

    Number(true) // = 1
    Number(false) // = 0
    
    0 讨论(0)
  • 2020-12-23 00:07

    ...or you can use +true and +false

    0 讨论(0)
  • 2020-12-23 00:08

    You can use ~~boolean, where boolean is (obviously) a boolean.

    ~~true  // 1
    ~~false // 0
    
    0 讨论(0)
  • 2020-12-23 00:15
    function translate(bool){
       return !!bool;
    }
    
    0 讨论(0)
  • 2020-12-23 00:18

    Lots of ways to do this

    // implicit cast
    +true; // 1
    +false; // 0
    // bit shift by zero
    true >>> 0; // 1, right zerofill
    false >>> 0; // 0
    true << 0; // 1, left
    false << 0; // 0
    // double bitwise NOT
    ~~true; // 1
    ~~false; // 0
    // bitwise OR ZERO
    true | 0; // 1
    false | 0; // 0
    // bitwise AND ONE
    true & 1; // 1
    false & 1; // 0
    // bitwise XOR ZERO, you can negate with XOR ONE
    true ^ 0; // 1
    false ^ 0; // 0
    // even PLUS ZERO
    true + 0; // 1
    false + 0; // 0
    // and MULTIPLICATION by ONE
    true * 1; // 1
    false * 1; // 0
    

    You can also use division by 1, true / 1; // 1, but I'd advise avoiding division where possible.

    Furthermore, many of the non-unary operators have an assignment version so if you have a variable you want converted, you can do it very quickly.

    You can see a comparison of the different methods with this jsperf.

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